﻿#include "mainwidgetfunction.h"

MainWidgetFunction::MainWidgetFunction(QObject *parent) :
    QObject(parent),
    m_pPromptDlg(NULL),
    m_shuttleDlg(NULL),
    m_pSystemManageDlg(NULL),
    m_pDebugInfoDlg(NULL)
{
    initialize();
    initializeLotData();//初始化物联网数据

    m_pPromptDlg = new PromptDialog();
    m_pPromptDlg->hide();

    connect(m_pPromptDlg, SIGNAL(siSpindleAction(int)),this, SLOT(slotSpindleAction(int)));
    connect(m_pPromptDlg, SIGNAL(siSpindleRotate(int)),this, SLOT(slotSpindleRotate(int)));
    connect(m_pPromptDlg, SIGNAL(siRotateRotate(int)),this, SLOT(slotRotateRotate(int)));
    connect(m_pPromptDlg, SIGNAL(siAutoPull(int)),this, SLOT(slotAutoPull(int)));
    connect(m_pPromptDlg, SIGNAL(siSpindleTime(int,int)),this, SLOT(slotSpindleResearch(int,int)));

    connect(m_pPromptDlg, SIGNAL(siUpdataCancel()),g_pMachine, SLOT(breakFileTrans()));
    connect(g_pMachine, SIGNAL(siTransProgress(u8,int,int)),this, SLOT(slotTransProgress(u8,int,int)));//升级主控进度条
    // connect(g_pLotMachine,SIGNAL(siConnectToMqtt()),this,SLOT(slotSendJsonToMqtt()));
    connect(g_pLotMachine,SIGNAL(siRunLotDataAction(QString)),this,SLOT(slotRunLotDataAction(QString)));

    //机器信息改变
    connect(g_pMachine, SIGNAL(siMcInfoChange()), this, SLOT(slotMCInfoChange()));
    //接收物联数据
    connect(g_pMachine, SIGNAL(siReceiveLotData()), this, SLOT(slotReceiveLotData()));

    m_shuttleDlg = new shuttlebottomlineDialog();
    m_shuttleDlg->hide();

    m_pSystemManageDlg = new SystemManageDialog();
    connect(m_pSystemManageDlg,SIGNAL(siClearProductStatis()),this,SLOT(slotClearProductStatis()));
    connect(m_pSystemManageDlg,SIGNAL(siCsvExport(int)),this,SLOT(slotCsvExport(int)));
    connect(m_pSystemManageDlg,SIGNAL(siCsvChangeErro( )),this,SLOT(slotJournalError( )));
    connect(m_pSystemManageDlg,SIGNAL(siCsvChangeBrea( )),this,SLOT(slotJournalBreakage( )));
    connect(m_pSystemManageDlg,SIGNAL(siCsvChangeDebug( )),this,SLOT(slotCsvChangeDebug()));
    connect(m_pSystemManageDlg,SIGNAL(siClearJournal()),this,SLOT(slotClearJournal()));
    connect(m_pSystemManageDlg,SIGNAL(siRefreshWifiList()),this,SLOT(slotRefreshWifiList()));

    connect(m_pSystemManageDlg,SIGNAL(siSetDynamicIP(QString)),this,SLOT(slotSetDynamicIP(QString)));
    connect(m_pSystemManageDlg,SIGNAL(siSetStaticIP(QString,QString,QString)),this,SLOT(slotSetStaticIP(QString,QString,QString)));

    m_pSystemManageDlg->hide();

    m_pDebugInfoDlg = new DebugInfoDialog();
    m_pDebugInfoDlg->hide();

    m_pTipsTimer = new QTimer(this);
    m_pTipsTimer->setInterval(14400000);//设置定时器时间间隔 4小时
    connect(m_pTipsTimer, SIGNAL(timeout()), this, SLOT(onTipsTimer()));

    //    测试物联网用
    //    connect(&timer, SIGNAL(timeout()), this, SLOT(slotReceiveLotData()));
    //    timer.setInterval(1000);
    //    timer.start();
}

MainWidgetFunction::~MainWidgetFunction()
{
    if(m_pPromptDlg != NULL)
    {
        delete m_pPromptDlg;
    }
    if(m_shuttleDlg != NULL)
    {
        delete m_shuttleDlg;
    }
    if(m_pSystemManageDlg != NULL)
    {
        delete m_pSystemManageDlg;
    }
    if(m_pDebugInfoDlg != NULL)
    {
        delete m_pDebugInfoDlg;
    }
}

void MainWidgetFunction::initialize()
{
    memset(&m_mcStatus,0,sizeof(MCStatus));
    m_curFileID = 1;// 当前文件ID
    m_filePath.clear();
    m_fileName.clear();
    m_getScore = 0;
    m_totalScore = 0;
    initializeLotInfo();
}

void MainWidgetFunction::initializeLotInfo()
{
    QDir apppath(qApp->applicationDirPath());
    QString iniPath = apppath.path() + apppath.separator() + "config.ini";
    QSettings setting(iniPath, QSettings::IniFormat); //QSettings能记录一些程序中的信息，下次再打开时可以读取出来
    m_getScore = setting.value("Progress/getScore").toInt();

    QString path = apppath.path() + apppath.separator() + CSV_PROGRESS;
    QFile file(path);
    if(!file.open(QIODevice::ReadOnly | QIODevice::Text))
    {
        qDebug() << "Open CSV file failed!";
        return;
    }

    QStringList strlist;
    strlist.clear();
    QTextStream out(&file);
    out.setCodec("GB2312");      //支持读取中文信息

    //遍历行
    for(int i = 0; !out.atEnd(); i++)
    {
        QString strLine = out.readLine();
        if(strLine.size() <= 0)
        {
            continue;
        }
        m_csvFileStrList.append(strLine);
        strlist = strLine.split(",", QString::SkipEmptyParts);    //根据","分隔开每行的列
        if(i > 0)   //第一行不执行操作
        {
            if (strlist.size() > COLUMN_SCORE)
            {
                QString code = strlist.at(COLUMN_CODE);
                QStringList strlist1 = code.split("_", QString::SkipEmptyParts);    //根据"_"分隔开每行的列
                int type = 0;
                if(strlist1.size() > 0)
                {
                    char *buf = strdup(strlist1[1].toLatin1().data());
                    sscanf (buf, "%x", &type);
                }
                s16 score = 0;
                score = strlist.at(COLUMN_SCORE).toInt();
                m_totalScore += score;
            }
        }
    }

    file.close();//关闭文件
}

//初始化物联网数据
void MainWidgetFunction::initializeLotData()
{
    memset(&m_mcLotData,0,sizeof(McLotData));
    memset(&m_HMILotData,0,sizeof(HMILotData));

    QString verStr = getVersionStr();
    memcpy(m_HMILotData.HMIVerStr, verStr.data(), verStr.length());   // 版本号

    u32 rackNum = g_pSettings->readFromIniFile("IOT/rackNumber").toInt();//机架号
    m_HMILotData.machineNumber = rackNum;   // 机架号

    u16 dProgress  =  g_pSettings->readFromIniFile("IOT/debugProgress").toInt();//调试进度
    m_HMILotData.debugProgress = dProgress;   //调试进度

    QString deliveryTime = g_pSettings->readFromIniFile("IOT/deliveryTime").toString();//工厂预计交货时间
    QByteArray arr = deliveryTime.toLocal8Bit();
    memcpy(m_HMILotData.deliveryTime, arr.data(), arr.size());   //交货日期

    //电机总数-先固定写为4个，如果后续变动较大，可把电机个数写为全局变量或从其他cpp中传参
    m_HMILotData.motorNum = 4;

    QString fileName = m_fileName;
    memcpy(m_HMILotData.fileName, fileName.data(), fileName.length());   // 文件名称
}

//优盘检测
QString MainWidgetFunction::detectUsb()
{
    QString usbPath = "";

#ifdef Q_OS_LINUX
    QDir dir(LINUXUSBPATH);
    if(!dir.exists())
    {
        usbPath = "";
    }
    else
    {
        usbPath = LINUXUSBPATH;
    }
#endif

#ifdef Q_OS_WIN
    QFileInfoList list =  QDir::drives();

    for(int i = 0; i<list.count(); i++)
    {
        UINT ret = GetDriveType((WCHAR *) list.at(i).filePath().utf16());
        if(ret == DRIVE_REMOVABLE)
        {
            usbPath = list.at(i).filePath();
            break;
        }
    }
#endif
    return usbPath;
}

s16 MainWidgetFunction::detectWifiConnect()
{
    s16 value = -1;
#ifdef Q_OS_LINUX
    QProcess cmd;
    QString cmdStr;
    cmdStr.clear();

    QString strCmdOut;
    strCmdOut.clear();

    QStringList lineStrList;
    lineStrList.clear();

    cmdStr = "wpa_cli -i wlan0 status";//查询wifi连接状态
    cmd.start(cmdStr);
    cmd.waitForStarted();
    cmd.waitForFinished();
    strCmdOut=QString::fromLocal8Bit(cmd.readAllStandardOutput());
    //qDebug()<<"strCmdOut"<<strCmdOut;
    lineStrList = strCmdOut.split("\n", QString::SkipEmptyParts);    //换行符
    //qDebug()<<"lineStrList.size()"<<lineStrList.size();
    for(int i = 0; i < lineStrList.size(); i++)
    {
        QStringList lineStr = lineStrList[i].split("=", QString::SkipEmptyParts);
        if(lineStr.size() >= 2)
        {
            QString str1 = lineStr[0];
            //qDebug()<<lineStrList[i];
            if(str1.indexOf("wpa_state") != -1)
            {
                QString str2 = lineStr[1];
                //qDebug()<<str2;
                if(str2.indexOf("COMPLETED") == -1)
                {
                    cmd.close();
                    value = -1;
                }
            }
            if(str1.indexOf("ip_address") != -1)
            {
                cmd.close();
                value = 1;
                break;
            }
        }
    }
    cmd.close();
#endif
    return value;
}

void MainWidgetFunction::systemUpgrade(int type)
{
    QString usbPath = detectUsb();
    if(usbPath.length() <= 0)
    {
        //优盘不存在
        m_pPromptDlg->initDialog(PromptDialog::BTN_OK);
        m_pPromptDlg->setTitleStr(tr("Prompt"));

        QString str;
        str = tr("USB flash drive is not detected!");//未检测到优盘！
        m_pPromptDlg->setContentStr(str);
        m_pPromptDlg->exec();
        return;
    }

    QDir apppath(qApp->applicationDirPath());
    QString targetDir = apppath.absolutePath() + apppath.separator();

    QDir dir (usbPath);
    dir.setFilter(QDir::Files | QDir::NoSymLinks);  // 设置类型过滤器，只为文件格式
    QFileInfoList fileList  = dir.entryInfoList();

    if(type == HMI_UPDATA)//界面升级
    {
        qDebug()<<"update 1";
        //界面文件、语言文件、RCC资源文件、打包的AUT文件
        for (int var = 0; var < fileList.size(); var++)
        {
#ifdef Q_OS_WIN
            if((fileList.at(var).fileName().toUpper().indexOf(APPNAME) != -1 &&
                fileList.at(var).suffix().toUpper() == "EXE") ||
                    fileList.at(var).fileName().toUpper().indexOf(".QM") != -1 ||
                    fileList.at(var).fileName().toUpper().indexOf(".RCC") != -1 ||
                    fileList.at(var).fileName().toUpper().indexOf(".AUT") != -1)
            {
                m_pSystemManageDlg->addItem(fileList.at(var).fileName());
            }
#endif

#ifdef Q_OS_LINUX
            if((fileList.at(var).fileName().toUpper().indexOf(APPNAME) != -1 &&
                fileList.at(var).suffix().toUpper().length() == 0) ||
                    fileList.at(var).fileName().toUpper().indexOf(".QM") != -1 ||
                    fileList.at(var).fileName().toUpper().indexOf(".RCC") != -1 ||
                    fileList.at(var).fileName().toUpper().indexOf(".AUT") != -1)
            {
                m_pSystemManageDlg->addItem(fileList.at(var).fileName());
            }
#endif
        }
        qDebug()<<"update 2";
    }
    else if(type == BACKUPS_UPDATA)//界面还原       ---------coco
    {
        //界面文件、语言文件、RCC资源文件、打包的AUT文件
        for (int var = 0; var < fileList.size(); var++)
        {
#ifdef Q_OS_WIN
            if((fileList.at(var).fileName().toUpper().indexOf(APPNAME) != -1 &&
                fileList.at(var).suffix().toUpper() == "EXE") ||
                    fileList.at(var).fileName().toUpper().indexOf(".QM") != -1 ||
                    fileList.at(var).fileName().toUpper().indexOf(".RCC") != -1 ||
                    fileList.at(var).fileName().toUpper().indexOf(".AUT") != -1)
            {
                m_pSystemManageDlg->addItem(fileList.at(var).fileName());
            }
#endif

#ifdef Q_OS_LINUX
            if((fileList.at(var).fileName().toUpper().indexOf(APPNAME) != -1 &&
                fileList.at(var).suffix().toUpper().length() == 0) ||
                    fileList.at(var).fileName().toUpper().indexOf(".QM") != -1 ||
                    fileList.at(var).fileName().toUpper().indexOf(".RCC") != -1 ||
                    fileList.at(var).fileName().toUpper().indexOf(".AUT") != -1)
            {
                m_pSystemManageDlg->addItem(fileList.at(var).fileName());
            }
#endif
        }
    }    // -------------coco
    else  if(type == MC_UPDATA)//主控升级
    {
        for (int var = 0; var < fileList.size(); var++)
        {
            if( fileList.at(var).suffix().toUpper() == "RNPU")
            {
                m_pSystemManageDlg->addItem(fileList.at(var).fileName());
            }
        }
        qDebug()<<"update 3";
    }
    else  if(type == PARA_IMPORT)//参数导入
    {
        QString fileSuffix = "PARADAT";

        for (int var = 0; var < fileList.size(); var++)
        {
            if( fileList.at(var).suffix().toUpper() == fileSuffix)
            {
                m_pSystemManageDlg->addItem(fileList.at(var).fileName());
            }
        }
        qDebug()<<"update 4";
    }
    //点击了确认按钮
    if(m_pSystemManageDlg->exec(type) == 1)
    {
        QString fileName =  m_pSystemManageDlg->getCurFile();

        if(type == HMI_UPDATA)//界面升级
        {
            QString sPath,tPath;
#ifdef Q_OS_WIN
            if(fileName.toUpper().indexOf(APPNAME) != -1 &&
                    fileName.toUpper().indexOf(".EXE") != -1)
            {
                sPath = usbPath + fileName;
                tPath = targetDir + WIN_APPNAME;

                //   ----- coco
                QString nowPath,oldPath,nPath;
                nowPath = targetDir +"XPlatForm.exe";
                oldPath = targetDir +  "version";
                QDir dir(oldPath);
                // 打开文件所在的路径
                if(!dir.exists())
                {
                    dir.mkdir(oldPath);//
                }
                //将文件复制到新建的version文件夹下
                nPath = targetDir + "/" + "version" + "/" + QFileInfo(tPath).fileName();
                QFile::copy( nowPath , nPath);

                // 获取当前日期和时间
                QDateTime currentDateTime = QDateTime::currentDateTime();
                QString formattedDateTime = currentDateTime.toString("yyyyMMdd_hhmmss");

                // 构造新的文件名
//                QString baseName = QFileInfo(nPath).baseName();
                QString newName = "XPlatForm";
                QString suffix = QFileInfo(nPath).suffix();
                QString newFileName = newName + "_" + formattedDateTime + "." + suffix;
                QString newFilePath = QFileInfo(nPath).absolutePath() + "/" + newFileName;

                // 重命名文件
                if (QFile::rename(nPath, newFilePath))
                {
                    qDebug() << "File renamed successfully from" << nPath << "to" << newFilePath;
                }
                else
                {
                    qDebug() << "Failed to rename file from" << nPath << "to" << newFilePath;
                }
                //   ----- coco


                qDebug()<<"HMI Update";
                qDebug()<<"sPath"<<sPath;
                qDebug()<<"tPath"<<tPath;

                QFile::remove(tPath);
                QFile::copy( sPath , tPath);
                qApp->exit();
            }
#endif

#ifdef Q_OS_LINUX
            if(fileName.toUpper().indexOf(APPNAME) != -1 &&
                    fileName.toUpper().indexOf(".EXE") == -1 &&
                    fileName.toUpper().indexOf(".AUT") == -1)//非aut打包文件
            {
                sPath = usbPath + fileName;
                tPath = targetDir + LINUX_APPNAME;

                //--------------coco
                QString nowPath,oldPath,nPath;
                nowPath = targetDir + LINUX_APPNAME;
                oldPath = targetDir +  "version";
                QDir dir(oldPath);
                // 打开文件所在的路径
                if(!dir.exists())
                {
                    dir.mkdir(oldPath);//
                }
                //将文件复制到新建的version文件夹下
                nPath = targetDir + "/" + "version" + "/" + QFileInfo(tPath).fileName();
                QFile::copy( nowPath , nPath);

                // 获取当前日期和时间
                QDateTime currentDateTime = QDateTime::currentDateTime();
                QString formattedDateTime = currentDateTime.toString("yyyyMMdd_hhmmss");

                // 构造新的文件名
                QString newName = "XPlatForm";
                QString newFileName = newName + "_" + formattedDateTime;
                QString newFilePath = QFileInfo(nPath).absolutePath() + "/" + newFileName;

                // 重命名文件
                if (QFile::rename(nPath, newFilePath))
                {
                    qDebug() << "File renamed successfully from" << nPath << "to" << newFilePath;
                }
                else
                {
                    qDebug() << "Failed to rename file from" << nPath << "to" << newFilePath;
                }
                //--------------coco

                qDebug()<<"HMI Update";
                qDebug()<<"sPath"<<sPath;
                qDebug()<<"tPath"<<tPath;

                QFile::remove(tPath);
                system("sync");
                QFile::copy( sPath , tPath);

                system("sync");
                system("reboot");
                qDebug()<<"reboot";
            }
#endif

            else if(fileName.toUpper().indexOf(".QM")  != -1 )
            {
                //增加语言包选择日期
                QString tPath;// 目标文件
                if(fileName.toUpper().indexOf("LAG-ZH")  != -1 )  //中文语言包   //XPlatForm-SEW-RP-LAG-ZH-V220511.qm
                {
                    tPath = targetDir +  "chinese.qm";  // 目标文件
                }
                else if(fileName.toUpper().indexOf("LAG-EN") != -1 ) // 英语
                {
                    tPath = targetDir +  "english.qm";
                }
                else if(fileName.toUpper().indexOf("LAG-ES") != -1 ) // 西班牙语
                {
                    tPath = targetDir + "spanish.qm";
                }
                else if(fileName.toUpper().indexOf("LAG-TK") != -1 ) // 土耳其语
                {
                    tPath = targetDir + "turkey.qm";
                }
                else if(fileName.toUpper().indexOf("LAG-RQ") != -1 ) // 葡萄牙语
                {
                    tPath = targetDir + "portugal.qm";
                }
                else if(fileName.toUpper().indexOf("LAG-FR") != -1 ) // 法语
                {
                    tPath = targetDir + "french.qm";
                }
                else
                {
                    tPath = targetDir + fileName ;
                }
                QString sPath = usbPath + fileName ;//源文件
                QString tPath1 = targetDir + "language.qm";

                qDebug()<<"Language Update";
                qDebug()<<"sPath"<<sPath;  //sPath "F:/chinese.qm"
                qDebug()<<"tPath"<<tPath;  //tPath "D:/work/workQT/XPlatform/Windows/debug\\chinese.qm"
                qDebug()<<"tPath1"<<tPath1;  //tPath1 "D:/work/workQT/XPlatform/Windows/debug\\language.qm"

                QFile::remove(tPath);
                QFile::remove(tPath1);

#ifdef Q_OS_LINUX
                system("sync");
#endif
                QFile::copy(sPath , tPath);//sPath复制到tPath
                QFile::copy(sPath , tPath1);

#ifdef Q_OS_WIN
                qApp->exit();
#endif
#ifdef Q_OS_LINUX
                system("sync");
                system("reboot");
#endif
            }

            else if(fileName.toUpper().indexOf(".RCC")  != -1 )
            {
                QString sPath = usbPath + fileName ;
                QString tPath = targetDir + "nxcui.rcc";

                qDebug()<<"RCC Update";
                qDebug()<<"sPath"<<sPath;
                qDebug()<<"tPath"<<tPath;

                QFile::remove(tPath );
#ifdef Q_OS_LINUX
                system("sync");
#endif
                QFile::copy(sPath , tPath);

#ifdef Q_OS_WIN
                qApp->exit();
#endif

#ifdef Q_OS_LINUX
                system("sync");
                system("reboot");
#endif
            }

            else if(fileName.toUpper().indexOf(".AUT") != -1)//界面打包文件(包括升级文件、语言包、RCC等)
            {
                QString strFile = usbPath + fileName;
                QFile file(strFile);
                file.open(QIODevice::ReadOnly);

                QByteArray AllData = file.readAll();
                HMIFileHead *fhead = (HMIFileHead*)(AllData.data());
                int filenum = fhead->fileNum;

                int bSize = 0;
                for(int j = 0; j < filenum; j++)
                {
                    int cSize = j*sizeof(HMIItemFileHead) + sizeof(HMIFileHead) + bSize;
                    HMIItemFileHead *ahead;
                    ahead = (HMIItemFileHead*)(AllData.data() + cSize);
                    QString fName = ahead->fileName;

                    int fileSize = ahead->fileSize;
                    if(fileSize <= 0)
                    {
                        return;
                    }
                    int sDataCheck = ahead->dataCheck;

                    cSize = cSize + sizeof(HMIItemFileHead);
                    QByteArray buf = AllData.mid(cSize,fileSize);
                    int tDataCheck = calcCheckSum32((u8*)buf.data(),fileSize);

                    bSize = bSize + fileSize;

                    //校验相同,查找相同的文件替换
                    if(sDataCheck == tDataCheck)
                    {
                        QString uFileName = targetDir + fName;
                        QFile uFile(uFileName);
                        QString cName = fName;

                        if(uFile.exists())//执行目录中存在U盘中的文件fileName
                        {
                            QString targetPath;
                            targetPath.clear();

#ifdef Q_OS_WIN
                            if(fName.toUpper().indexOf(APPNAME) != -1 &&
                                    fName.toUpper().indexOf(".EXE") != -1)
                            {
                                targetPath = targetDir + WIN_APPNAME;
                            }
#endif

#ifdef Q_OS_LINUX
                            if(fName.toUpper().indexOf(APPNAME) != -1 &&
                                    fName.toUpper().indexOf(".EXE") == -1)
                            {
                                targetPath = targetDir + LINUX_APPNAME;
                                cName = LINUX_APPNAME;
                            }
#endif

#if(0)
                            if(fName.toUpper().indexOf(APPNAME) != -1)
                            {
#ifdef Q_OS_WIN
                                targetPath = targetDir + WIN_APPNAME;
#endif
#ifdef Q_OS_LINUX

                                targetPath = targetDir + LINUX_APPNAME;
                                cName = LINUX_APPNAME;
#endif
                            }
#endif
                            else//其他文件
                            {
                                targetPath = uFileName;
                            }

                            QFile::remove(targetPath);
                            QFile tFile(targetPath);

                            if(tFile.open(QIODevice::WriteOnly) == false)
                            {
                                return;
                            }
                            tFile.write(buf);

                            qDebug()<<"AUT Update";
                            qDebug()<<"targetPath"<<targetPath;

#ifdef Q_OS_LINUX
                            QString str = "chmod 777 " + cName;
                            system(str.toLatin1());
#endif
                        }
                        else//不存在
                        {
                            QString targetPath;
                            targetPath.clear();

#ifdef Q_OS_WIN
                            if(fName.toUpper().indexOf(APPNAME) != -1 &&
                                    fName.toUpper().indexOf(".EXE") != -1)
                            {
                                targetPath = targetDir + WIN_APPNAME;
                            }
#endif

#ifdef Q_OS_LINUX
                            if(fName.toUpper().indexOf(APPNAME) != -1 &&
                                    fName.toUpper().indexOf(".EXE") == -1)
                            {
                                targetPath = targetDir + LINUX_APPNAME;
                                cName = LINUX_APPNAME;
                            }
#endif

#if(0)
                            if(fName.toUpper().indexOf(APPNAME) != -1)
                            {
#ifdef Q_OS_WIN
                                targetPath = targetDir + WIN_APPNAME;
#endif
#ifdef Q_OS_LINUX

                                targetPath = targetDir + LINUX_APPNAME;
                                cName = LINUX_APPNAME;
#endif
                            }
#endif
                            else//其他文件
                            {
#ifdef Q_OS_WIN
                                if(fName.toUpper().indexOf(APPNAME) != -1 &&
                                        fName.toUpper().indexOf(".EXE") == -1)
                                {
                                    continue;
                                }
#endif

#ifdef Q_OS_LINUX
                                if(fName.toUpper().indexOf(APPNAME) != -1 &&
                                        fName.toUpper().indexOf(".EXE") != -1)
                                {
                                    continue;
                                }
#endif
                                targetPath = uFileName;
                            }

                            QFile tFile(targetPath);

                            if(tFile.open(QIODevice::WriteOnly) == false)
                            {
                                return;
                            }
                            tFile.write(buf);

                            qDebug()<<"not exist"<<cName;
                            qDebug()<<"targetPath"<<targetPath;

#ifdef Q_OS_LINUX
                            QString str = "chmod 777 " + cName;
                            system(str.toLatin1());
#endif
                        }
                    }
                    else
                    {
                        m_pPromptDlg->initDialog(PromptDialog::BTN_OK);
                        m_pPromptDlg->setTitleStr(tr("Prompt"));
                        m_pPromptDlg->setContentStr(tr("The program is corrupted, please re-upgrade after replacing the program!"));  //程序已损坏，请更换程序后重新升级！
                        m_pPromptDlg->exec();
                        return;
                    }
                }
                file.close();

#ifdef Q_OS_LINUX
                qDebug()<<"reboot before";
                system("sync");
                system("reboot");
                qDebug()<<"reboot end";
#endif

                //需放在linux重启命令后面
#ifdef Q_OS_WIN
                qDebug()<<"qApp->exit()";
                qApp->exit();
#endif
            }
            else
            {
                //所选文件非升级文件
                //文件格式错误，请重新选择!
                m_pPromptDlg->initDialog(PromptDialog::BTN_OK);
                m_pPromptDlg->setTitleStr(tr("Prompt"));

                QString str;
                str = tr("The file format is wrong, please select again!");//文件格式错误，请重新选择!
                m_pPromptDlg->setContentStr(str);
                m_pPromptDlg->exec();
            }
        }
        else  if(type == MC_UPDATA)//主控升级
        {
            if(fileName.toUpper().indexOf(".RNPU") != -1)
            {
                QString uPath = usbPath + fileName;

                qDebug()<<"RNPU update";
                qDebug()<<"uPath"<<uPath;

                AppFileHead appHead ;
                memset(&appHead , 0 , sizeof(appHead));
                QFile file(uPath);

                u8 * pBuff = (u8 *) malloc(file.size());
                qDebug() << "file.size()" << file.size();

                if(file.size() <= 0)
                {
                    //文件格式错误，请重新选择!
                    m_pPromptDlg->initDialog(PromptDialog::BTN_OK);
                    m_pPromptDlg->setTitleStr(tr("Prompt"));

                    QString str;
                    str = tr("File bytes are 0, please check the file!");//文件字节为0，请检查文件!
                    m_pPromptDlg->setContentStr(str);
                    m_pPromptDlg->exec();
                    return;
                }

                file.open(QIODevice::ReadOnly);
                file.read( (char *)pBuff , file.size()) ;
                file.close();

                int nameSize = uPath.toUtf8().size() ;
                if( nameSize >  32 )
                {
                    nameSize = 32;
                }
                memcpy(appHead.fileName , uPath.toUtf8().data() , nameSize);
                appHead.dataSize = file.size();
                appHead.dataChecksum = calcCheckSum32(pBuff , file.size());

                static int nID = 0;
                if( g_pMachine->isConnected() == 3)
                {
                    g_pMachine->sendAPPFileProc(FILE_TYPE_PGM,
                                                0,
                                                nID++,
                                                appHead ,
                                                pBuff
                                                );
                }
                free(pBuff);
            }
        }
        else  if(type == PARA_IMPORT)//参数导入
        {
            QString uPath = usbPath + fileName;

            qDebug()<<"Para Import";
            qDebug()<<"uPath"<<uPath;

            QFile paraFile(uPath);
            if(!paraFile.exists())
            {
                return;
            }

            paraFile.open(QIODevice::ReadOnly);

            if(paraFile.size() != 0)
            {
                int readSize = 0;
                // 将文件 读取成结构体
                ParaFile paraFileStruct;
                memset(&paraFileStruct,0,sizeof(ParaFile));
                int paraSize = 0;

                readSize =  paraFile.read((char*)&paraFileStruct,sizeof(ParaFile));
                paraSize = sizeof(ParaFile);
                paraFile.close();

                if(readSize != paraFile.size())
                {
                    //文件大小不匹配,无效的参数文件
                    m_pPromptDlg->initDialog(PromptDialog::BTN_OK);
                    m_pPromptDlg->setTitleStr(tr("Prompt"));

                    QString str;
                    str = (tr("File size not match, invalid file!"));//文件大小不匹配,无效的参数文件!
                    m_pPromptDlg->setContentStr(str);
                    m_pPromptDlg->exec();
                    return;
                }

                if( readSize !=  paraSize)
                {
                    //文件大小不匹配,无效的参数文件
                    m_pPromptDlg->initDialog(PromptDialog::BTN_OK);
                    m_pPromptDlg->setTitleStr(tr("Prompt"));

                    QString str;
                    str = (tr("File size not match, invalid file!"));//文件大小不匹配,无效的参数文件!
                    m_pPromptDlg->setContentStr(str);
                    m_pPromptDlg->exec();
                    return;
                }

                // 参数被正确的读取
                if(
                        ( paraFileStruct.s_head[0] == 'P' )
                        && ( paraFileStruct.s_head[1] == 'A' )
                        && ( paraFileStruct.s_head[2] == 'R' )
                        && ( paraFileStruct.s_head[3] == 'A' )
                        && ( paraFileStruct.s_type    == 0   )
                        && ( paraFileStruct.s_len     == 4096 )
                        )
                {
                    unsigned short i_crc = calcCrc16( (unsigned char *)  paraFileStruct.s_para_buff , paraFileStruct.s_len);

                    if( paraFileStruct.s_crc != i_crc )
                    {
                        //数据校验错误,无效的参数文件
                        m_pPromptDlg->initDialog(PromptDialog::BTN_OK);
                        m_pPromptDlg->setTitleStr(tr("Prompt"));

                        QString str;
                        str = (tr("Data check error, invalid file!"));//数据校验错误,无效的参数文件!
                        m_pPromptDlg->setContentStr(str);
                        m_pPromptDlg->exec();
                        return;
                    }
                    //将 一个文件 拆分成两个 缓冲区
                    unsigned char mac_config  [1024] ;
                    unsigned char work_config [1024] ;
                    unsigned char pre_mac_config  [1024] ;
                    unsigned char pre_work_config [1024] ;

                    // 清空
                    memset(  mac_config  ,  0 ,  1024 ) ;
                    memset(  work_config ,  0 ,  1024 ) ;
                    memset(  pre_mac_config  ,  0 ,  1024 ) ;
                    memset(  pre_work_config ,  0 ,  1024 ) ;

                    memcpy(  work_config ,  paraFileStruct.s_para_buff , 1024 ) ;
                    memcpy(  mac_config  ,  ((char*)paraFileStruct.s_para_buff) + 1024 , 1024 ) ;
                    memcpy(  pre_mac_config  ,  ((char*)paraFileStruct.s_para_buff) + 2048 , 1024 ) ;
                    memcpy(  pre_work_config  ,  ((char*)paraFileStruct.s_para_buff) + 3072 , 1024 ) ;

                    g_pMachine->setMcPara((ParaStruct *) mac_config);
                    g_pMachine->setWkPara((ParaStruct *) work_config);
                    g_pMachine->setMcPrePara((ParaStruct *) pre_mac_config);
                    g_pMachine->setWkPrePara((ParaStruct *) pre_work_config);

                    QString str;
                    m_pPromptDlg->initDialog(PromptDialog::BTN_OK);
                    m_pPromptDlg->setTitleStr(tr("Prompt"));
                    str = (tr("Parameters imported successfully!"));//参数导入成功!
                    m_pPromptDlg->setContentStr(str);
                    m_pPromptDlg->exec();
                    return;
                }
                else
                {
                    //文件头不匹配,无效的参数文件!
                    m_pPromptDlg->initDialog(PromptDialog::BTN_OK);
                    m_pPromptDlg->setTitleStr(tr("Prompt"));

                    QString str;
                    str = (tr("File head not match, invalid file!"));//文件头不匹配,无效的参数文件!
                    m_pPromptDlg->setContentStr(str);
                    m_pPromptDlg->exec();
                    return;
                }
            }
        }
    }
}
// ---------coco
//备份升级
void MainWidgetFunction::systembackupUpgrade(int type)
{
    QDir apppath(qApp->applicationDirPath());
    QString targetDir = apppath.absolutePath() + apppath.separator();

    QString localPath = targetDir +  "version";
    QDir dir(localPath);
    // 打开文件所在的路径
    if(!dir.exists())
    {
        dir.mkdir(localPath);//
    }

    dir.setFilter(QDir::Files | QDir::NoSymLinks);  // 设置类型过滤器，只为文件格式
    QFileInfoList fileList  = dir.entryInfoList();
    if(type == BACKUPS_UPDATA)//界面还原
    {
        for (int var = 0; var < fileList.size(); var++)
        {
#ifdef Q_OS_WIN
            if((fileList.at(var).fileName().toUpper().indexOf(APPNAME) != -1 &&
                fileList.at(var).suffix().toUpper() == "EXE") ||
                    fileList.at(var).fileName().toUpper().indexOf(".QM") != -1 ||
                    fileList.at(var).fileName().toUpper().indexOf(".RCC") != -1 ||
                    fileList.at(var).fileName().toUpper().indexOf(".AUT") != -1)
            {
                m_pSystemManageDlg->addItem(fileList.at(var).fileName());
            }
#endif

#ifdef Q_OS_LINUX
            if((fileList.at(var).fileName().toUpper().indexOf(APPNAME) != -1 &&
                fileList.at(var).suffix().toUpper().length() == 0) ||
                    fileList.at(var).fileName().toUpper().indexOf(".QM") != -1 ||
                    fileList.at(var).fileName().toUpper().indexOf(".RCC") != -1 ||
                    fileList.at(var).fileName().toUpper().indexOf(".AUT") != -1)
            {
                m_pSystemManageDlg->addItem(fileList.at(var).fileName());
            }
#endif
        }
    }

    //点击了确认按钮
    if(m_pSystemManageDlg->exec(type) == 1)
    {
        QString fileName =  m_pSystemManageDlg->getCurFile();
        QString nowPath,oldPath,newPath;

        if(type == BACKUPS_UPDATA)//界面还原
        {
#ifdef Q_OS_WIN
            if(fileName.toUpper().indexOf(APPNAME) != -1 &&
                    fileName.toUpper().indexOf(".EXE") != -1)
            {
                nowPath = targetDir + "XPlatForm.exe";

                oldPath = targetDir + "/" + "version" + "/" + fileName;

                newPath = targetDir + fileName;

                QFile::remove(nowPath);
                QFile::copy(oldPath , newPath);//

                // 构造新的文件名

                QString newName = "XPlatForm1";     //为做区分多加一个1
                QString suffix = QFileInfo(newPath).suffix();
                QString newFileName = newName + "." + suffix;
                QString newFilePath = QFileInfo(newPath).absolutePath() + "/" + newFileName;

                // 重命名文件
                if (QFile::rename(newPath, newFilePath))
                {
                    qDebug() << "File renamed successfully from" << newPath << "to" << newFilePath;
                }
                else
                {
                    qDebug() << "Failed to rename file from" << newPath << "to" << newFilePath;
                }

                qApp->exit();
            }
#endif

#ifdef Q_OS_LINUX
            if(fileName.toUpper().indexOf(APPNAME) != -1 &&
                    QFileInfo(fileName).suffix().length() == 0)
            {
                nowPath = targetDir + LINUX_APPNAME;

                oldPath = targetDir + "/" + "version" + "/" + fileName;

                newPath = targetDir + fileName;

                QFile::remove(nowPath);
                system("sync");
                QFile::copy(oldPath , newPath);//
                system("sync");

                // 构造新的文件名
                QString newName = "OPRT_CP";     //
                QString newFilePath = QFileInfo(newPath).absolutePath() + "/" + newName;

                // 重命名文件
                if (QFile::rename(newPath, newFilePath))
                {
                    qDebug() << "File renamed successfully from" << newPath << "to" << newFilePath;
                }
                else
                {
                    qDebug() << "Failed to rename file from" << newPath << "to" << newFilePath;
                }

                system("reboot");
                qDebug()<<"reboot";
            }
#endif
        }


    }


}
// -------coco  window上原来的exe,在remove函数下无法移除,Linux没问题

s16 MainWidgetFunction::refreshWifiList(QStringList &wifiStrList,s16 scan)
{
    if(scan == 0){}//为了去掉编译警告
    wifiStrList.clear();

    QProcess cmd;
    QString cmdStr;
    cmdStr.clear();
    QString strCmdOut;
    strCmdOut.clear();
    QStringList lineStrList;
    lineStrList.clear();

    m_pPromptDlg->initDialog(PromptDialog::BTN_OK);
    m_pPromptDlg->setTitleStr(tr("Prompt"));

#ifdef Q_OS_LINUX
    cmdStr = "ifconfig";//查看wlan0初始化是否成功
    cmd.start(cmdStr);
    cmd.waitForStarted();
    cmd.waitForFinished();
    strCmdOut=QString::fromLocal8Bit(cmd.readAllStandardOutput());
    lineStrList = strCmdOut.split("\n", QString::SkipEmptyParts);    //换行符
    int initFlag = 0;
    for(int i = 0; i < lineStrList.size(); i++)
    {
        QString lineStr = lineStrList[i];
        if(lineStr.indexOf("wlan0") != -1)
        {
            initFlag = 1;
            break;
        }
    }
    if(initFlag == 0)
    {
        m_pPromptDlg->setContentStr(tr("Failed to initialize wlan0!"));//初始化wlan0失败！
        m_pPromptDlg->exec();
        return -1;
    }

    if(scan != 0)
    {
        cmdStr = "wpa_cli -i wlan0 scan";//搜索可见wifi
        cmd.start(cmdStr);
        cmd.waitForStarted();
        cmd.waitForFinished();
        strCmdOut=QString::fromLocal8Bit(cmd.readAllStandardOutput());
        int flag = 0;
        while(strCmdOut.toUpper().indexOf("OK") == -1)
        {
            cmdStr = "wpa_cli -i wlan0 scan";//搜索可见wifi
            cmd.start(cmdStr);
            cmd.waitForStarted();
            cmd.waitForFinished();
            strCmdOut=QString::fromLocal8Bit(cmd.readAllStandardOutput());
            flag++;
            if(flag>=100){
               break;
            }
        }
    }

    cmdStr = "wpa_cli -i wlan0 scan_result";//获取搜索结果
    cmd.start(cmdStr);
    cmd.waitForStarted();
    cmd.waitForFinished();
    strCmdOut=QString::fromLocal8Bit(cmd.readAllStandardOutput());
    lineStrList = strCmdOut.split("\n", QString::SkipEmptyParts);//换行符
    for(int i = 0; i < lineStrList.size(); i++)
    {
        //qDebug()<<i<<lineStrList[i];
        QStringList lineStr = lineStrList[i].split("\t", QString::SkipEmptyParts);//tap

        if(lineStr.size() >= 2 && lineStr[lineStr.size()-1].indexOf("]") == -1)
        {
            QString str = lineStr[lineStr.size()-1].remove(QRegExp("^ +\\s*"));//正则表达式去掉空格
            s16 ifExist = 0;
            for(s16 m = 0; m < wifiStrList.size(); m++)
            {
                if(wifiStrList[m] == str)
                {
                    ifExist = 1;
                    break;
                }
            }
            if(ifExist == 0)
            {
                wifiStrList.append(str);
            }
        }
    }
    if(wifiStrList.size() <= 0)
    {
        m_pPromptDlg->setContentStr(tr("Failed to search for WiFi list. Please try again later!"));//搜索wifi列表失败，请稍后重试！
        m_pPromptDlg->exec();
        return -1;
    }
#endif
    return 1;
}

QString MainWidgetFunction::getIpSegment(bool bl)
{
    m_pPromptDlg->initDialog(PromptDialog::BTN_OK);
    m_pPromptDlg->setTitleStr(tr("Prompt"));

    QString ipStr;
    ipStr.clear();
    if(bl == true){}//为了去掉编译警告
    //linux下查询wifi连接状态
#ifdef Q_OS_LINUX
    s16 value = -1;
    QProcess cmd;
    QString cmdStr;
    cmdStr.clear();

    QString strCmdOut;
    strCmdOut.clear();

    QStringList lineStrList;
    lineStrList.clear();

    cmdStr = "wpa_cli -i wlan0 status";//查询wifi连接状态
    cmd.start(cmdStr);
    cmd.waitForStarted();
    cmd.waitForFinished();
    strCmdOut=QString::fromLocal8Bit(cmd.readAllStandardOutput());
    //qDebug()<<"strCmdOut"<<strCmdOut;
    lineStrList = strCmdOut.split("\n", QString::SkipEmptyParts);    //换行符
    //qDebug()<<"lineStrList.size()"<<lineStrList.size();
    for(int i = 0; i < lineStrList.size(); i++)
    {
        QStringList lineStr = lineStrList[i].split("=", QString::SkipEmptyParts);
        if(lineStr.size() >= 2)
        {
            QString str1 = lineStr[0];
            //qDebug()<<lineStrList[i];
            if(str1.indexOf("wpa_state") != -1)
            {
                QString str2 = lineStr[1];
                //qDebug()<<str2;
                if(str2.indexOf("COMPLETED") == -1)
                {
                    cmd.close();
                }
            }
            if(str1.indexOf("ip_address") != -1)
            {
                ipStr = lineStr[1].remove(QRegExp("^ +\\s*"));//正则表达式去掉空格-IP
                cmd.close();
                value = 1;
                break;
            }
        }
    }
    cmd.close();

    if(value >= 0)
    {
        QString modeStr;
        modeStr.clear();
        if(bl == false)
        {
            modeStr = tr("dynamic");//动态
        }
        else if(bl == true)
        {
            modeStr = tr("static");//静态
        }

        ipStr = ipStr + "(" + modeStr + ")";
    }
    else
    {
        if(bl == true)
        {
            m_pPromptDlg->setContentStr(tr("Failed to obtain IP.  Please check the settings!"));//获取IP失败，请检查设置！
            m_pPromptDlg->exec();
        }
    }
#endif
    return ipStr;
}

//参数导入
void MainWidgetFunction::funImportParameter(QString tStyle)
{
    m_pSystemManageDlg->setTypeLogo(tStyle);
    m_pSystemManageDlg->setMainTitle(tr("Parameter Import"));
    m_pSystemManageDlg->setSubTitle(tr("Auxiliary Function > Parameter Import"));
    m_pSystemManageDlg->initDialog();
    systemUpgrade(PARA_IMPORT);
}

//主控升级
void MainWidgetFunction::funMCUpgrade(QString tStyle)
{
    m_pSystemManageDlg->setTypeLogo(tStyle);
    m_pSystemManageDlg->setMainTitle(tr("MC Upgrade"));
    m_pSystemManageDlg->setSubTitle(tr("Auxiliary Function > MC Upgrade"));
    m_pSystemManageDlg->initDialog();
    systemUpgrade(MC_UPDATA);
}

//界面升级
void MainWidgetFunction::funHMIUpgrade(QString tStyle)
{
    m_pSystemManageDlg->setTypeLogo(tStyle);
    m_pSystemManageDlg->setMainTitle(tr("HMI Upgrade"));
    m_pSystemManageDlg->setSubTitle(tr("Auxiliary Function > HMI Upgrade"));
    m_pSystemManageDlg->initDialog();

    systemUpgrade(HMI_UPDATA);
}

//界面还原
void MainWidgetFunction::funHMIBackupsUpgrade(QString tStyle)
{
    m_pSystemManageDlg->setTypeLogo(tStyle);
    m_pSystemManageDlg->setMainTitle(tr("HMI backups Upgrade"));
    m_pSystemManageDlg->setSubTitle(tr("Auxiliary Function > HMI backups Upgrade 66"));
    m_pSystemManageDlg->initDialog();

    systembackupUpgrade(BACKUPS_UPDATA);
}

void MainWidgetFunction::funWIFI(QString tStyle)
{
    QStringList wifiStrList;
    wifiStrList.clear();
    s16 rel = refreshWifiList(wifiStrList);
    if(rel > 0)
    {
        m_pSystemManageDlg->setTypeLogo(tStyle);
        m_pSystemManageDlg->setMainTitle(tr("WIFI"));
        m_pSystemManageDlg->setSubTitle(tr("Auxiliary Function > WIFI"));

        bool mode = false;//动态获取IP方式
        QString iniPath = WIFIINIPATH;
        QSettings setting(iniPath,QSettings::IniFormat);
        QString wifiName = QByteArray::fromBase64(setting.value("WIFI/default_ssid").toByteArray());
        QString wifiPass = QByteArray::fromBase64(setting.value("WIFI/default_passwd").toByteArray());
        mode = setting.value("WIFI/static_mode").toBool();

        QString ip = getIpSegment(mode);
        if(ip.length() > 0)//已连接
        {
            m_pSystemManageDlg->setWifiInfo(ip,wifiName,wifiPass,mode);
            m_pSystemManageDlg->initDialog(1);
            for(s16 i = 0; i < wifiStrList.size(); i++)
            {
                m_pSystemManageDlg->addItem(wifiStrList.at(i));
            }
            emit siWifiState(true);
        }
        else//未连接
        {
            m_pSystemManageDlg->initDialog(1);
            for(s16 i = 0; i < wifiStrList.size(); i++)
            {
                m_pSystemManageDlg->addItem(wifiStrList.at(i));
            }
            emit siWifiState(false);
        }
        m_pSystemManageDlg->exec();
    }
}

//参数导出
void MainWidgetFunction::funExportParameter()
{
    QString usbPath = detectUsb();
    if(usbPath.length() <= 0)
    {
        //优盘不存在
        m_pPromptDlg->initDialog(PromptDialog::BTN_OK);
        m_pPromptDlg->setTitleStr(tr("Prompt"));

        QString str;
        str = tr("USB flash drive is not detected!");//未检测到优盘！
        m_pPromptDlg->setContentStr(str);
        m_pPromptDlg->exec();
        return;
    }

    MCInfo info1 = g_pMachine->getMcInfo();
    QString software_ver;
    software_ver.sprintf("%s",info1.softwareVerStr);
    qDebug()<<info1.softwareVerStr;
    qDebug()<<info1.buildInfoStr;

    QStringList i_sof = software_ver.split(" ");//读取空格之前的版本信息
    QString i_info = i_sof[0] ;
    QString i_para = "Epara_";
    QString paradat = ".paradat";
    QString i_time = QDateTime::currentDateTime().toString("_yyMMdd_hhmmss");//时间日期

    QString strName = i_para + i_info + i_time + paradat;
    QString paraFileName = usbPath + strName;
    QFile::remove (paraFileName) ;

#ifdef Q_OS_LINUX
    system("sync");
#endif


    char para_mc [ 1024 ];
    char para_wk [ 1024 ];

    char pre_para_mc [ 1024 ];
    char pre_para_wk [ 1024 ];

    memcpy(para_mc , (u8*) (&(g_pMachine->getMcPara())) ,  1024 );
    memcpy(para_wk , (u8*) (&(g_pMachine->getWkPara())) ,  1024 );

    memcpy(pre_para_mc , (u8*) (&(g_pMachine->getPreMcPara())) ,  1024 );
    memcpy(pre_para_wk , (u8*) (&(g_pMachine->getPreWkPara())) ,  1024 );

    //两个缓冲区,输出成一个参数文件
    // 转换结构体 开始
    ParaFile paraFileStruct ;
    memset(&paraFileStruct,0,sizeof(ParaFile)) ;

    paraFileStruct.s_head[0]  = 'P';
    paraFileStruct.s_head[1]  = 'A';
    paraFileStruct.s_head[2]  = 'R';
    paraFileStruct.s_head[3]  = 'A';

    paraFileStruct.s_type = 0   ;
    paraFileStruct.s_len = 4096 ;

    memcpy( paraFileStruct.s_para_buff                      , para_wk , 1024  );
    memcpy( (char *) (paraFileStruct.s_para_buff) + 1024    , para_mc ,  1024 );
    memcpy( (char *) (paraFileStruct.s_para_buff) + 2048    , pre_para_mc ,  1024 );
    memcpy( (char *) (paraFileStruct.s_para_buff) + 3072    , pre_para_wk ,  1024 );

    paraFileStruct.s_crc = calcCrc16( (u8 * ) paraFileStruct.s_para_buff  ,  4096 ) ;
    // 转换结构体 结束

    // 保存文件 开始
    QFile file(paraFileName);
    file.open(QIODevice::ReadWrite | QIODevice::Truncate);
    file.write((char*)&paraFileStruct,sizeof(ParaFile));
    file.flush();
    file.close();
    // 保存文件 结束

#ifdef Q_OS_LINUX
    system("sync");
#endif

    //参数导出成功
    m_pPromptDlg->initDialog(PromptDialog::BTN_OK);
    m_pPromptDlg->setTitleStr(tr("Prompt"));

    QString str;
    str = tr("Parameters exported successfully!");//参数导出成功！
    m_pPromptDlg->setContentStr(str);
    m_pPromptDlg->exec();
    return;
}

//全部归零
void MainWidgetFunction::funAllToZero()
{
    m_pPromptDlg->initDialog(PromptDialog::BTN_OK_CANCEL);
    m_pPromptDlg->setTitleStr(tr("All to zero"));//全部归零

    QString str;
    str = tr("The machine is about to move, please pay attention to safety!");//机器即将运动，请注意安全！
    m_pPromptDlg->setContentStr(str);

    if(m_pPromptDlg->exec() == 1)
    {
        if(g_pMachine != NULL)
        {
            g_pMachine->allToZero();
        }
    }
}

//产量清零
void MainWidgetFunction::funResetOutput()
{
    m_pPromptDlg->initDialog(PromptDialog::BTN_OK_CANCEL);
    m_pPromptDlg->setTitleStr(tr("All to reset"));//产量清零

    QString str;
    str = tr("Whether to reset the output?");//是否重置产量？
    m_pPromptDlg->setContentStr(str);

    if(m_pPromptDlg->exec() == 1)
    {
        if(g_pMachine != NULL)
        {
            g_pMachine->resetOutput();
        }
    }
}

//流程复位
void MainWidgetFunction::funAllToReset()
{
    m_pPromptDlg->initDialog(PromptDialog::BTN_OK_CANCEL);
    m_pPromptDlg->setTitleStr(tr("All to reset"));//流程复位

    QString str;
    str = tr("If all process to reset?");//是否全部流程复位?
    m_pPromptDlg->setContentStr(str);

    if(m_pPromptDlg->exec() == 1)
    {
        if(g_pMachine != NULL)
        {
            qDebug()<<"MainWidgetFunction::funAllToReset() >>>>>>>>>>>>>>>> g_pMachine->allToReset();";
            g_pMachine->allToReset();
        }
    }
}

//主轴点动
void MainWidgetFunction::funSpindleJog()
{
    m_pPromptDlg->initDialog(PromptDialog::BTN_OK_CANCEL);
    m_pPromptDlg->setTitleStr(tr("Spindle jog"));//主轴点动
    QString str;
    str = tr("The machine is about to move, please pay attention to safety!");//机器即将运动，请注意安全！
    m_pPromptDlg->setContentStr(str);

    if(m_pPromptDlg->exec() == 1)
    {
        if(g_pMachine != NULL)
        {
            g_pMachine->sewJog();
        }
    }
}

//主轴旋转
void MainWidgetFunction::funSpindleRotate()
{
    m_pPromptDlg->initDialog(PromptDialog::BTN_SPINDLE_ROTATE);
    m_pPromptDlg->setTitleStr(tr("Spindle rotate angle"));//主轴旋转角度
    m_pPromptDlg->exec();               // coco
//    if (m_pPromptDlg->exec() == 1)
//    {
//        s32 val = m_pPromptDlg->getSpindleRotateAngle();

//        if(g_pMachine != NULL)
//        {
//        }
//    }
}

//旋转电机旋转
void MainWidgetFunction::funRotateRotate()
{
    m_pPromptDlg->initDialog(PromptDialog::BTN_ROTATE_ROTATE);
    m_pPromptDlg->setTitleStr(tr("Rotating motor rotation angle"));//旋转电机旋转角度
    m_pPromptDlg->exec();
//    if (m_pPromptDlg->exec() == 1)
//    {
//        //s32 val = m_pPromptDlg->getSpindleRotateAngle();

//        if(g_pMachine != NULL)
//        {
//        }
//    }
}

//回工作点
void MainWidgetFunction::funBackWorkPoint()
{
    m_pPromptDlg->initDialog(PromptDialog::BTN_OK_CANCEL);
    m_pPromptDlg->setTitleStr(tr("Back work point"));//回工作点

    QString str;
    str = tr("The machine is about to move, please pay attention to safety!");//机器即将运动，请注意安全！
    m_pPromptDlg->setContentStr(str);

    if(m_pPromptDlg->exec() == 1)
    {
        if(g_pMachine != NULL)
        {
            g_pMachine->gotoWorkPos();
        }
    }
}

//回原点（回零点（回绣框原点））
void MainWidgetFunction::funBackToOrigin()
{
    m_pPromptDlg->initDialog(PromptDialog::BTN_OK_CANCEL);
    m_pPromptDlg->setTitleStr(tr("Back to zero"));//回原点

    QString str;
    str = tr("The machine is about to move, please pay attention to safety!");//机器即将运动，请注意安全！
    m_pPromptDlg->setContentStr(str);

    if(m_pPromptDlg->exec() == 1)
    {
        if(g_pMachine != NULL)
        {
            g_pMachine->gotoZeroPos();
        }
    }
}

void MainWidgetFunction::funBackToCuttringPoint()
{

    m_pPromptDlg->initDialog(PromptDialog::BTN_OK_CANCEL);
    m_pPromptDlg->setTitleStr(tr("Back to Cuttring"));//回切割点

    QString str;
    str = tr("The machine is about to move, please pay attention to safety!");//机器即将运动，请注意安全！
    m_pPromptDlg->setContentStr(str);

    if(m_pPromptDlg->exec() != 1) return;

    if(g_emMacType == MACHINE_FLATCUTTINGMAC || g_emMacType == MACHINE_FLYFLATCUTTING)
    {
        if(g_pMachine !=NULL)
        {
            //从配置文件中读取切割点
            int x = g_pSettings->readFromIniFile("FlatPanel/AnchorPointX").toInt();
            int y = g_pSettings->readFromIniFile("FlatPanel/AnchorPointY").toInt();
            g_pMachine->moveFrameTo(x,y);
        }
    }
}

//定起始点
void MainWidgetFunction::funSetStartPoint(QString filePath,int x,int y,int showFlag, bool allToReset, bool isSendPatternHead)
{
    if(filePath.length() <= 0)
    {
        return;
    }

    m_pPromptDlg->initDialog(PromptDialog::BTN_OK_CANCEL);
    m_pPromptDlg->setTitleStr(tr("Set start point"));//定起始点
    QString str = tr("Whether to set the current point as the start point?");//是否将当前点设置为起始点?
    m_pPromptDlg->setContentStr(str);
    int setFlag = 1;
    if(showFlag == 1)
    {
        setFlag = m_pPromptDlg->exec();
    }

    if(setFlag == 1)
    {
        int oldBeginX, oldBeginY;
        oldBeginX = oldBeginY = 0;
        if(g_pCurEmbData != NULL)
        {
            oldBeginX = g_pCurEmbData->getBeginX();
            oldBeginY = g_pCurEmbData->getBeginY();
            g_pCurEmbData->setStartPosition(x,y);
        }

        if(isSendPatternHead)
            sendPatternHead(filePath);//发送花样ds16头文件

        //每次点击选择花样的时候才会生成ds16数据，其他时候就是给下位机发头文件
        //dsr,dst整个文件->中间数据->ds16
        int wx,wy;
        if(g_emMacType == MACHINE_FIVEHEADPRECISIONSEWING)
        {
            wx = x - g_pCurEmbData->getAnchorX();
            wy = y - g_pCurEmbData->getAnchorY();

            writePonitToFile(filePath,wx,wy);  //将新的起始点，机头，写回到（dst，dsr）源文件中
        }
        //粗线布线机
        else if(g_emMacType == MACHINE_THICK_WIRING)
        {
            writePonitToFile(filePath,x,y);    //  coco  将新起始点写回头文件
        }
        else
        {
            wx = x - oldBeginX - g_pCurEmbData->getAnchorX();
            wy = y - oldBeginY - g_pCurEmbData->getAnchorY();

            writePonitToFile(filePath,wx,wy);  //将新的起始点，机头，写回到（dst，dsr）源文件中
        }

        //流程复位
        if(allToReset)
            g_pMachine->allToReset();

        slotCalMachineProgress(CSV_00_CODE_2);
    }
}

//定上料点  -rq
void MainWidgetFunction::funSetFeedPoint()
{
    m_pPromptDlg->initDialog(PromptDialog::BTN_OK_CANCEL);
    m_pPromptDlg->setTitleStr(tr("set feeding point"));//定上料点

    QString str;
    str = tr("Whether to set the current point as the feeding point?");//是否将当前点设置为上料点?
    m_pPromptDlg->setContentStr(str);

    if(m_pPromptDlg->exec() == 1)
    {
        if(g_pMachine != NULL)
        {
            g_pMachine->setFeedPos();
        }
    }
}
//回上料点
void MainWidgetFunction::funBackFeedPoint()
{
    m_pPromptDlg->initDialog(PromptDialog::BTN_OK_CANCEL);
    m_pPromptDlg->setTitleStr(tr("Back feed point"));//回上料点

    QString str;
    str = tr("The machine is about to move, please pay attention to safety!");//机器即将运动，请注意安全！
    m_pPromptDlg->setContentStr(str);

    if(m_pPromptDlg->exec() == 1)
    {
        if(g_pMachine != NULL)
        {
            g_pMachine->gotoFeedPos();
        }
    }
}

// 回起针点
void MainWidgetFunction::funBackStartPoint()
{
    m_pPromptDlg->initDialog(PromptDialog::BTN_OK_CANCEL);

    //提示为起绣点设置，绣花机中定起绣点调用的是定定位点，
    //所以提示回起绣点(回起绣点暂未使用)
    m_pPromptDlg->setTitleStr(tr("Back embroidery point"));//回起针点
    if(g_emMacType ==MACHINE_FLATCUTTINGMAC || g_emMacType == MACHINE_FLYFLATCUTTING)
         m_pPromptDlg->setTitleStr(tr("Back strart point"));//回起点
    QString str;
    str = tr("The machine is about to move, please pay attention to safety!");//机器即将运动，请注意安全！
    m_pPromptDlg->setContentStr(str);

    if(m_pPromptDlg->exec() == 1)
    {
        if(g_pMachine != NULL)
        {
            g_pMachine->gotoStartPos();
            slotCalMachineProgress(CSV_00_CODE_3);
        }
    }
}

void MainWidgetFunction::funGotoFinish()
{
    m_pPromptDlg->initDialog(PromptDialog::BTN_OK_CANCEL);
    m_pPromptDlg->setTitleStr(tr("goto Finish"));//回结束点

    QString str;
    str = tr("The machine is about to move, please pay attention to safety!");//机器即将运动，请注意安全！
    m_pPromptDlg->setContentStr(str);

    if(m_pPromptDlg->exec() == 1)
    {
        if(g_pMachine != NULL)
        {
            g_pMachine->gotoFinish();
        }
    }
}

//定偏移点
void MainWidgetFunction::funSetOffsetPoint()
{
    m_pPromptDlg->initDialog(PromptDialog::BTN_OK_CANCEL);
    m_pPromptDlg->setTitleStr(tr("Set offset point"));//定偏移点

    QString str;
    str = tr("Whether to set the current point as the offset point?");//是否将当前点设置为偏移点?
    m_pPromptDlg->setContentStr(str);

    if(m_pPromptDlg->exec() == 1)
    {
        if(g_pMachine != NULL)
        {
            g_pMachine->setOffsetPos();
        }
    }
}

//回偏移点
void MainWidgetFunction::funBackOffsetPoint()
{
    m_pPromptDlg->initDialog(PromptDialog::BTN_OK_CANCEL);
    m_pPromptDlg->setTitleStr(tr("Back offset point"));//回偏移点

    QString str;
    str = tr("The machine is about to move, please pay attention to safety!");//机器即将运动，请注意安全！
    m_pPromptDlg->setContentStr(str);

    if(m_pPromptDlg->exec() == 1)
    {
        if(g_pMachine != NULL)
        {
            g_pMachine->gotoOffsetPos();
        }
    }
}

//边框检查
void MainWidgetFunction::funBorderCheck()
{
    m_pPromptDlg->initDialog(PromptDialog::BTN_OK_CANCEL);
    m_pPromptDlg->setTitleStr(tr("Border check"));//边框检查

    QString str;
    str = tr("The machine is about to move, please pay attention to safety!");//机器即将运动，请注意安全！
    m_pPromptDlg->setContentStr(str);

    if(m_pPromptDlg->exec() == 1)
    {
        if((m_mcStatus.workStatus & WORK_STA_BUSY) != 0)    // 下位机在执行动作
        {
            return;
        }

        g_pMachine->checkFrame();    // 发给下位机，边框检查
        slotCalMachineProgress(CSV_00_CODE_4);
    }
}

//手动剪线
void MainWidgetFunction::funManualTrim()
{
    m_pPromptDlg->initDialog(PromptDialog::BTN_OK_CANCEL);
    m_pPromptDlg->setTitleStr(tr("Trim"));//剪线
    QString str;
    str = tr("The machine is about to cut the thread, please pay attention to safety!");//机器即将剪线，请注意安全！
    m_pPromptDlg->setContentStr(str);
    if(m_pPromptDlg->exec() == 1)
    {
        if(g_pMachine != NULL)
        {
            //g_pMachine->sewCutThread();
        }
    }
}

//设置可工作区域
void MainWidgetFunction::funSetWorkArea()
{
    m_pPromptDlg->initDialog(PromptDialog::BTN_WORK_AREA);
    m_pPromptDlg->setTitleStr(tr("Setting workable area"));//设置可工作区域
    //int areaValue = m_pPromptDlg->getArea();
    if(m_pPromptDlg->exec() == 1)
    {
        if(g_pMachine != NULL)
        {
        }
    }
}

//剪刀开合
void MainWidgetFunction::funCutterOpenAndClose()
{
    m_pPromptDlg->initDialog(PromptDialog::BTN_OK_CANCEL);
    m_pPromptDlg->setTitleStr(tr("Lower cutter"));//下剪线
    QString str;
    str = tr("The scissors are about to move, please pay attention to safety!");//剪刀即将动作，请注意安全！
    m_pPromptDlg->setContentStr(str);
    if(m_pPromptDlg->exec() == 1)
    {
        if(g_pMachine != NULL)
        {
        }
    }
}

//空走边框
void MainWidgetFunction::funSimulateFrame()
{
    m_pPromptDlg->initDialog(PromptDialog::BTN_OK_CANCEL);
    m_pPromptDlg->setTitleStr(tr("Simulate frame"));//空走边框

    QString str;
    str = tr("The machine is about to move, please pay attention to safety!");//机器即将运动，请注意安全！
    m_pPromptDlg->setContentStr(str);

    if(m_pPromptDlg->exec() == 1)
    {
        if((m_mcStatus.workStatus & WORK_STA_BUSY) != 0)    // 下位机在执行动作
        {
            return;
        }

        g_pMachine->simulateFrame();    // 发给下位机，空走边框
    }
}

//流程复位
void MainWidgetFunction::funProcessReset()
{
    m_pPromptDlg->initDialog(PromptDialog::BTN_OK_CANCEL);
    m_pPromptDlg->setTitleStr(tr("Process reset"));//流程复位

    QString str;
    str = tr("The machine is about to reset, please pay attention to safety!");//机器即将流程复位，请注意安全！
    m_pPromptDlg->setContentStr(str);

    if(m_pPromptDlg->exec() == 1)
    {
        if(g_pMachine != NULL)
        {
            g_pMachine->allToReset();
        }
    }
}

//手动加油
void MainWidgetFunction::funManualOil()
{
    m_pPromptDlg->initDialog(PromptDialog::BTN_OK_CANCEL);
    m_pPromptDlg->setTitleStr(tr("Manual oil"));//手动加油

    QString str;
    str = tr("The machine is about to oil!");//机器即将加油！
    m_pPromptDlg->setContentStr(str);

    if(m_pPromptDlg->exec() == 1)
    {
        if(g_pMachine != NULL)
        {
            g_pMachine->manualOil(1);
        }
        slotCalMachineProgress(CSV_00_CODE_6);
    }
}

//梭盘计数复位
void MainWidgetFunction::funShuttleChange()
{
    m_pPromptDlg->initDialog(PromptDialog::BTN_OK_CANCEL);
    m_pPromptDlg->setTitleStr(tr("Shuttle count reset"));//梭盘计数复位

    QString str;
    str = tr("The machine is about to change the shuttle automatically!");//机器即将自动换梭！
    m_pPromptDlg->setContentStr(str);

    if(m_pPromptDlg->exec() == 1)
    {
        if(g_pMachine != NULL)
        {
            g_pMachine->shuttleCounter();
        }
    }
}

//框架归零
void MainWidgetFunction::funGotoZeroPos()
{
    m_pPromptDlg->initDialog(PromptDialog::BTN_OK_CANCEL);
    m_pPromptDlg->setTitleStr(tr("Goto zero pos"));//框架归零

    QString str;
    str = tr("The machine is about to move, please pay attention to safety!");//机器即将运动，请注意安全！
    m_pPromptDlg->setContentStr(str);

    if(m_pPromptDlg->exec() == 1)
    {
        if(g_pMachine != NULL)
        {
            g_pMachine->gotoZeroPos();
        }
    }
}

//定工作范围
void MainWidgetFunction::funSetWorkRange()
{
    m_pPromptDlg->initDialog(PromptDialog::BTN_OK_CANCEL);
    m_pPromptDlg->setTitleStr(tr("Set work range"));//定工作范围

    QString str;
    str = tr("If automatically set work range?");//是否自动定工作范围?
    m_pPromptDlg->setContentStr(str);

    if(m_pPromptDlg->exec() == 1)
    {
        if(g_pMachine != NULL)
        {
        }
    }
}

void MainWidgetFunction::sendPatternHead(QString filePath)
{
    if(DATA_FORMATE == DATA_DS16)
    {
        //获取文件头并重新发送文件头
        DataDs16FileHead *pDs16Head = g_pCurEmbData->getDsDatHead();
        g_pMachine->setFilePara(0, m_curFileID, (DataFilePara&)*pDs16Head);
    }
    else if(DATA_FORMATE == DATA_DS8)
    {
        QString ds8FilePath = filePath + ".ds8";
        QFile file(ds8FilePath);

        if(file.exists())//存在ds8文件
        {
            if(!file.open(QIODevice::ReadOnly))
            {
                qDebug() << "open file fail when read";
                return;
            }

            QByteArray ary = file.readAll();
            DataDs16FileHead *pDs8Head = (DataDs16FileHead *)(ary.data());

            DataDs16FileHead *pDs16Head = g_pCurEmbData->getDsDatHead();
            pDs8Head->anchorX = pDs16Head->anchorX;
            pDs8Head->anchorY = pDs16Head->anchorY;
            pDs8Head->beginX = pDs16Head->beginX;
            pDs8Head->beginY = pDs16Head->beginY;
            pDs8Head->beginR = pDs16Head->beginR;
            //pDs8Head->combineMode = pDs16Head->combineMode;
            pDs8Head->maxX = pDs16Head->maxX;
            pDs8Head->maxY = pDs16Head->maxY;
            pDs8Head->minX = pDs16Head->minX;
            pDs8Head->minY = pDs16Head->minY;

            g_pMachine->setFilePara(0, m_curFileID, (DataFilePara&)*pDs8Head);

            file.close();
        }
        else
        {
            QByteArray ds16dat = g_pCurEmbData->getDsDat();//获得ds16数据

            QByteArray ds8dat;
            ds8dat.clear();

            // ds16数据
            int size = ds16dat.size();
            if (size <= (int)sizeof(DataDs16FileHead))
            {
                qDebug("data less then head size");
                return;
            }
            DataDs16FileHead * pDs16Head = (DataDs16FileHead *)(ds16dat.data());
            ds8dat.append((char*)pDs16Head,sizeof(DataDs16FileHead));

            int datasize = size - sizeof(DataDs16FileHead);
            if (datasize <= 0)
            {
                qDebug("ds16 dataBegin err");
                return;
            }
            int stepsize = datasize/sizeof(Ds16Item);
            if (stepsize <= 0)
            {
                qDebug("ds16 data size err");
                return;
            }
            Ds16Item *pData = (Ds16Item *)(ds16dat.data() + sizeof(DataDs16FileHead));
            Ds16Item * dataPtr = pData;

            u8 ctrl,attr;
            s16 dx,dy,dr;
            Ds8Item ds8Item;

            for (int i = 0; i < stepsize; i++)
            {
                ctrl = dataPtr->ctrl;
                attr = dataPtr->attr;
                dx = dataPtr->dx;
                dy = dataPtr->dy;
                dr = dataPtr->dr;

                ds8Item.ctrl = ctrl;
                ds8Item.attr = attr;
                ds8Item.dx = dx;
                ds8Item.dy = dy;
                ds8Item.dr = dr;

                ds8dat.append((char*)&ds8Item,sizeof(Ds8Item));

                dataPtr++;
            }

            //发送ds8数据
            DataDs16FileHead * pDs8Head = (DataDs16FileHead *)(ds8dat.data());
            Ds8Item *tData = (Ds8Item *)(ds8dat.data() + sizeof(DataDs16FileHead));

            //重新生成文件头
            pDs8Head->dataSize = pDs8Head->itemNums*sizeof(Ds8Item);    // 数据字节数
            pDs8Head->bytesPerItem = sizeof(Ds8Item);           // 每项占的字节数
            pDs8Head->dataChecksum = calcCheckSum32((u8 *)(tData) , pDs8Head->dataSize);;	// 数据累加校验和
            pDs8Head->checkCrc = calcCrc16((u8 *)(pDs8Head), HEAD_FIX_INFO_LEN); // 前面6个字段的CRC校验，（6个字段分别为：文件名称，字节数，项个数，每项字节数，每块字节数，数据累加和的CRC校验值）

            g_pMachine->setFilePara(0, m_curFileID, (DataFilePara&)*pDs8Head);
        }
    }
}

//选择花样后发送数据并显示大图
void MainWidgetFunction::sendPatternData(QString filePath,int type)
{
    m_filePath = filePath;

    //保存最后一次绣作的花样路径到配置文件中
    if(g_pSettings != NULL)
    {
        g_pSettings->writeToIniFile("Pattern/name",filePath);
    }

    if(DATA_FORMATE == DATA_DS16)
    {
        sendDs16PatternData(type);//发送ds16数据
    }
    else if(DATA_FORMATE == DATA_DS8)
    {
        convertDs16ToDs8AndSend(filePath,type);//将ds16数据转换为ds8数据并发送
    }
}

void MainWidgetFunction::funBottomDetect()
{
    m_pPromptDlg->initDialog(PromptDialog::BTN_BOTTOM);
    m_pPromptDlg->setTitleStr(tr("Bottom line detection"));
    m_pPromptDlg->exec();
}

void MainWidgetFunction::funFaceDetect()
{
    m_pPromptDlg->initDialog(PromptDialog::BTN_FACE);
    m_pPromptDlg->setTitleStr(tr("Face line detection"));
    m_pPromptDlg->exec();
}

void MainWidgetFunction::funExitRoot()
{
    m_pPromptDlg->initDialog(PromptDialog::BTN_OK);
    m_pPromptDlg->setTitleStr(tr("Prompt"));
    g_emUser = operate;
    m_pPromptDlg->setContentStr(tr("Exit successfully!"));//成功退出!
    m_pPromptDlg->exec();
}

void MainWidgetFunction::funGetMCVersionInfo()
{
    m_pPromptDlg->initDialog(PromptDialog::BTN_OK);
    m_pPromptDlg->setTitleStr(tr("System info"));
    m_pPromptDlg->setContentInfoShow();

    m_pPromptDlg->exec();
}

void MainWidgetFunction::funProductStatistics(QString tStyle,QString filePath,int patternBreakLineNum)
{
    m_pSystemManageDlg->setTypeLogo(tStyle);
    m_pSystemManageDlg->setMainTitle(tr("Production statistics"));//生产统计
    m_pSystemManageDlg->setSubTitle(tr("Auxiliary Function > Production statistics"));//辅助功能 > 生产统计
    m_pSystemManageDlg->initDialog();

    m_filePath = filePath;
    QFileInfo file(m_filePath);
    QString fileName = file.fileName();
    m_fileName = fileName;
    addProductStatisInfo(patternBreakLineNum);
    m_pSystemManageDlg->exec(PRODUCTSTATIS);
}

//错误日志
void MainWidgetFunction::slotJournalError()
{
    //m_pSystemManageDlg->setTypeLogo(tStyle);
    m_pSystemManageDlg->setMainTitle(tr("Error Log"));//错误日志
    m_pSystemManageDlg->setSubTitle(tr("Auxiliary Function > Error Log"));//辅助功能 > 错误日志
    m_pSystemManageDlg->initDialog();
    addJournalInfoError();
    //m_pSystemManageDlg->exec(JOURNALERROR);//显示窗体
}

//断线日志
void MainWidgetFunction::slotJournalBreakage()
{
    //m_pSystemManageDlg->setTypeLogo(tStyle);
    m_pSystemManageDlg->setMainTitle(tr("Breakage Log"));//断线日志
    m_pSystemManageDlg->setSubTitle(tr("Auxiliary Function > Breakage Log"));//辅助功能 > 断线日志
    m_pSystemManageDlg->initDialog();
    addJournalInfoBreakage();
    //m_pSystemManageDlg->exec(JOURNALBREAKAGE);//显示窗体
}

void MainWidgetFunction::slotCsvChangeDebug()
{
    //m_pSystemManageDlg->setTypeLogo(tStyle);
    m_pSystemManageDlg->setMainTitle(tr("Debug Info"));//调试信息
    m_pSystemManageDlg->setSubTitle(tr("Auxiliary Function >Debug Info"));//辅助功能 > 调试信息
    m_pSystemManageDlg->initDialog();
    addJournalInfoDebug();
    //m_pSystemManageDlg->exec(JOURNALBREAKAGE);//显示窗体
}

//错误日志
void MainWidgetFunction::funJournalError(QString tStyle)
{
    m_pSystemManageDlg->setTypeLogo(tStyle);
    m_pSystemManageDlg->setMainTitle(tr("ErrorLog"));//错误日志
    m_pSystemManageDlg->setSubTitle(tr("Auxiliary Function > ErrorLog"));//辅助功能 > 错误日志
    m_pSystemManageDlg->initDialog();
    addJournalInfoError();
    m_pSystemManageDlg->exec(JOURNAL);//显示窗体
}

void MainWidgetFunction::funDebugInfo()
{
    m_pDebugInfoDlg->initDialog();
    m_pDebugInfoDlg->addListInfo();
    m_pDebugInfoDlg->exec();//显示窗体
}

void MainWidgetFunction::funSoftwareAuthor()
{
    if (g_pMachine != NULL)
    {
        if(g_pMachine->isConnected() == 3)
        {
            g_pMachine->getInfoFromMachine();
        }
        else
        {
            m_pPromptDlg->initDialog(PromptDialog::BTN_OK);
            m_pPromptDlg->setTitleStr(tr("Prompt"));
            m_pPromptDlg->setContentStr(tr("No connection"));
            m_pPromptDlg->exec();
            return;
        }
    }

    // 设置板卡ID值的显示
    m_pPromptDlg->initDialog(PromptDialog::BTN_WARRANT);
    m_pPromptDlg->setTitleStr(tr("Warrant"));
    m_pPromptDlg->setContentWarrantShow();
    m_pPromptDlg->exec();
}

//报错信息
int MainWidgetFunction::funErrorPrompt(QString info)
{
    int ret = 0;
    m_pPromptDlg->initDialog(PromptDialog::BTN_OK);
    m_pPromptDlg->setTitleStr(tr("Prompt"));
    //QString errInfo= errcode+info;
    m_pPromptDlg->setContentStr(info);
    if(m_pPromptDlg->exec() == 1)
    {
        g_pMachine->cleanError();
    }
    return ret;
}

int MainWidgetFunction::funDetectBreakLineStatus()
{
    //断线状态
    QString allStr;
    allStr.clear();
    QString headStr;
    headStr.clear();

    QString infoStr;//记录到csv的内容
    infoStr.clear();

    int ret = 0;
    if(g_pMachine != NULL)
    {
        ParaStruct mcParaValues;
        mcParaValues = g_pMachine->getMcPara();
    }
    g_pSettings->writeToCsv(infoStr,TYPE_BREAK);//保存到csv

    return ret;
}

void MainWidgetFunction::funSetPromptDlgVisibleFalse()
{
    if(m_pPromptDlg->isVisible())
    {
        m_pPromptDlg->done(1);
    }
}

//底线计数复位
void MainWidgetFunction::funBottomLineCountReset()
{
    m_pPromptDlg->initDialog(PromptDialog::BTN_OK_CANCEL);
    m_pPromptDlg->setTitleStr(tr("Prompt"));
    m_pPromptDlg->setContentStr(tr("Is the bottom line count reset?")); //是否底线计数复位?
    if(m_pPromptDlg->exec() == 1)
    {
        g_pMachine->resetBobbinCounter(); // 底线计数复位
    }
}

//手自动工作状态切换 0:手动  1:自动
void MainWidgetFunction::funManualOrAutoSwitch(s16 val)
{
    m_pPromptDlg->initDialog(PromptDialog::BTN_OK_CANCEL);
    m_pPromptDlg->setTitleStr(tr("Prompt"));
    if(val == 0)
    {
        m_pPromptDlg->setContentStr(tr("Are you sure to ManualSwitch?"));  //是否手动工作状态切换?
        if(m_pPromptDlg->exec() == 1)
        {
            g_pMachine->setToManualWork();
        }
    }
    else if( val ==1)
    {
        m_pPromptDlg->setContentStr(tr("Are you sure to AutoSwitch?")); //是否自动工作状态切换?
        if(m_pPromptDlg->exec() == 1)
        {
            g_pMachine->setToAutoWork();
        }
    }
}

void MainWidgetFunction::slotCalMachineProgress(s16 csvCode,s16 type)
{
    int per = 0;
    int ifPress = 0;

    for(int i = 1; i < m_csvFileStrList.size(); i++)
    {
        QStringList strlist = m_csvFileStrList[i].split(",", QString::SkipEmptyParts);    //根据","分隔开每行的列
        if(strlist.size() > 0)
        {
            QString code = strlist.at(COLUMN_CODE);
            QStringList strlist1 = code.split("_", QString::SkipEmptyParts);    //根据"_"分隔开每行的列
            int infoCode = 0;
            int csvType = 0;
            if(strlist1.size() >= 2)
            {
                char *bufCode = strdup(strlist1[2].toLatin1().data());
                sscanf (bufCode, "%x", &infoCode);

                char *bufType = strdup(strlist1[1].toLatin1().data());
                sscanf (bufType, "%x", &csvType);
            }

            if(infoCode == csvCode && type == csvType)
            {
                QStringList strlist2 = m_csvFileStrList[i].split(",", QString::SkipEmptyParts);    //根据","分隔开每行的列
                if(COLUMN_PRESSNUM < strlist2.size())
                {
                    ifPress = strlist2.at(COLUMN_PRESSNUM).toInt()+1;
                    strlist2[COLUMN_PRESSNUM] = QString::number(ifPress);
                    QString str;
                    for(int m = 0; m < strlist2.size(); m++)
                    {
                        str.append(strlist2[m]);
                        if(m != strlist2.size() - 1)
                        {
                            str.append(",");
                        }
                    }
                    m_csvFileStrList[i] = str;

                    //如果按钮没被点击过就加入百分比的计算
                    if(ifPress == 1)
                    {
                        per += strlist2.at(COLUMN_SCORE).toInt();
                    }
                }

                m_getScore += per;

                if(per != 0)
                {
                    if(m_totalScore == 0)
                    {
                        m_totalScore = 1;
                    }

                    sendDataToGateway(csvCode,type);
                }

                break;
            }
        }
    }

    if(ifPress == 1)
    {
        QTextCodec::setCodecForLocale(QTextCodec::codecForName("GBK"));

        QByteArray array;
        array.clear();
        for(int j = 0; j < m_csvFileStrList.size(); j++)
        {
            QString str = m_csvFileStrList[j];
            array.append(str.toLocal8Bit());
            if(j != m_csvFileStrList.size() - 1)
            {
                array.append('\n');
            }
        }

        QDir apppath(qApp->applicationDirPath());
        QString path = apppath.path() + apppath.separator() + CSV_PROGRESS;
        QFile file(path);
        if (file.open(QIODevice::WriteOnly | QIODevice::Truncate | QIODevice::Text))
        {
            file.write(array);
#ifdef Q_OS_LINUX
            system("sync");
#endif
        }
        file.close();

        QString iniPath = apppath.path() + apppath.separator() + "config.ini";
        QSettings setting(iniPath, QSettings::IniFormat); //QSettings能记录一些程序中的信息，下次再打开时可以读取出来
        setting.setValue("Progress/getScore",m_getScore); //记录路径到QSetting中保存

        QTextCodec::setCodecForLocale(QTextCodec::codecForName("UTF-8"));
    }
}

//发送ds16花样数据
void MainWidgetFunction::sendDs16PatternData(int type)
{
    QByteArray & ds16dat = g_pCurEmbData->getDsDat();

    // ds16数据（转换的）
    int size = ds16dat.size();
    if (size <= (int)sizeof(DataDs16FileHead))
    {
        qDebug("data less then head size");
        return;
    }
    DataDs16FileHead * pDs16Head = (DataDs16FileHead *)(ds16dat.data());

    qDebug()<<"fileid 2"<<pDs16Head->fileid;

    int datasize = size - sizeof(DataDs16FileHead);
    if (datasize <= 0)
    {
        qDebug("ds16 dataBegin err");
        return;
    }
    int stepsize = datasize/sizeof(Ds16Item);
    if (stepsize <= 0)
    {
        qDebug("ds16 data size err");
        return;
    }
    Ds16Item *pData = (Ds16Item *)(ds16dat.data() + sizeof(DataDs16FileHead));

#if(0)
    Ds16Item item;
    item.dx = pData->dx;
    item.dy = pData->dy;
    item.dr = pData->dr;
    if(item.dx == 0 && item.dy == 0)
    {
        ds16dat.remove(0,sizeof(Ds16Item));
        pData = (Ds16Item *)(ds16dat.data() + sizeof(DataDs16FileHead));
    }
#endif

    //发送ds16数据
    m_curFileID++;
    if ((m_curFileID & 0xffff) == 0)
    {
        m_curFileID = 1;
    }
    if(g_pMachine != NULL)
    {
        g_pMachine->sendFileProc(type, 0, m_curFileID, pDs16Head, (u8*)pData);
    }
}

//将ds16数据转换为ds8数据并发送
void MainWidgetFunction::convertDs16ToDs8AndSend(QString filePath,int type)
{
    QByteArray ds16dat = g_pCurEmbData->getDsDat();//获得ds16数据

    QByteArray ds8dat;
    ds8dat.clear();

    // ds16数据
    int size = ds16dat.size();
    if (size <= (int)sizeof(DataDs16FileHead))
    {
        qDebug("data less then head size");
        return;
    }
    DataDs16FileHead * pDs16Head = (DataDs16FileHead *)(ds16dat.data());
    ds8dat.append((char*)pDs16Head,sizeof(DataDs16FileHead));

    int datasize = size - sizeof(DataDs16FileHead);
    if (datasize <= 0)
    {
        qDebug("ds16 dataBegin err");
        return;
    }
    int stepsize = datasize/sizeof(Ds16Item);
    if (stepsize <= 0)
    {
        qDebug("ds16 data size err");
        return;
    }
    Ds16Item *pData = (Ds16Item *)(ds16dat.data() + sizeof(DataDs16FileHead));
    Ds16Item * dataPtr = pData;

    u8 ctrl,attr;
    s16 dx,dy,dr;
    Ds8Item ds8Item;

    for (int i = 0; i < stepsize; i++)
    {
        ctrl = dataPtr->ctrl;
        attr = dataPtr->attr;
        dx = dataPtr->dx;
        dy = dataPtr->dy;
        dr = dataPtr->dr;

        ds8Item.ctrl = ctrl;
        ds8Item.attr = attr;
        ds8Item.dx = dx;
        ds8Item.dy = dy;
        ds8Item.dr = dr;

        ds8dat.append((char*)&ds8Item,sizeof(Ds8Item));

        dataPtr++;
    }

#if(1)
    //保存成ds8文件
    QString ds8FilePath = filePath + ".ds8";
    QFile file(ds8FilePath);
    if(file.exists())//存在ds8文件
    {
        QFile::remove(ds8FilePath);
    }
#endif

    //发送ds8数据
    DataDs16FileHead * pDs8Head = (DataDs16FileHead *)(ds8dat.data());
    Ds8Item *tData = (Ds8Item *)(ds8dat.data() + sizeof(DataDs16FileHead));

    //重新生成文件头
    pDs8Head->dataSize = pDs8Head->itemNums*sizeof(Ds8Item);    // 数据字节数
    pDs8Head->bytesPerItem = sizeof(Ds8Item);           // 每项占的字节数
    pDs8Head->dataChecksum = calcCheckSum32((u8 *)(tData) , pDs8Head->dataSize);;	// 数据累加校验和
    pDs8Head->checkCrc = calcCrc16((u8 *)(pDs8Head), HEAD_FIX_INFO_LEN); // 前面6个字段的CRC校验，（6个字段分别为：文件名称，字节数，项个数，每项字节数，每块字节数，数据累加和的CRC校验值）

    m_curFileID++;
    if ((m_curFileID & 0xffff) == 0)
    {
        m_curFileID = 1;
    }
    g_pMachine->sendFileProc(type, 0, m_curFileID, pDs8Head, (u8*)tData);

    if(!file.open(QIODevice::WriteOnly | QIODevice::Truncate))
    {
        qDebug() << "open file fail when wirte, path =" << filePath;
        return;
    }
    else
    {
        file.write(ds8dat);
        file.close();
    }
}

void MainWidgetFunction::addProductStatisInfo(int patternBreakLineNum)
{
    //刷新生产统计信息
    m_pSystemManageDlg->initDialog();

    QString itemStr = tr("Total number of patterns processed: ") + QString::number(m_mcStatus.outCounter);//总共加工花样数量:
    m_pSystemManageDlg->addItem(itemStr);
    itemStr = tr("Total number of embroidery: ") + QString::number(m_mcStatus.needleNum);//总刺绣针数:
    m_pSystemManageDlg->addItem(itemStr);

    itemStr = tr("Pattern name: ") + m_fileName;//花样名称:
    m_pSystemManageDlg->addItem(itemStr);

    itemStr = tr("Pattern break line num: ") + QString::number(patternBreakLineNum);//花样断线次数:
    m_pSystemManageDlg->addItem(itemStr);

    ParaStruct mcParaValues;
    mcParaValues = g_pMachine->getMcPara();
    int needleBreakNum = 0;
    //机头断线次数:
    itemStr = tr("Head ") + QString::number(1) + tr(" break line num: ") + QString::number(needleBreakNum);// 机头断线次数:
    m_pSystemManageDlg->addItem(itemStr);
}

void MainWidgetFunction::addJournalInfoError()
{
    //刷新信息
    m_pSystemManageDlg->initDialog();
    m_pSystemManageDlg->addListError();//读取csv列表
}

void MainWidgetFunction::addJournalInfoBreakage()
{
    //刷新信息
    m_pSystemManageDlg->initDialog();
    m_pSystemManageDlg->addListBreakage();//读取csv列表
}

void MainWidgetFunction::addJournalInfoDebug()
{
    //刷新信息
    m_pSystemManageDlg->initDialog();
    m_pSystemManageDlg->addListDebug();//读取csv列表
}

QString MainWidgetFunction::getCompileDateTime()
{
    const char *pMonth[] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
    const char date[12] = __DATE__; // 取编译日期

    int i;
    int month, year, day;
    month = year = day = 0;
    for(i = 0; i < 12; i++)
    {
        if(memcmp(date, pMonth[i], 3) == 0)
        {
            month = i + 1;
            break;
        }
    }
    year = (unsigned char)atoi(date + 9); // date[9]为2位年份, date[7]为完整年份
    day = (unsigned char)atoi(date + 4);  // 日期

    QString str;
    str.sprintf("%02d%02d%02d", year, month, day);
    return str;
}

//组成json键值对
QString MainWidgetFunction::compositionJson(QString key, QString value)
{
    QString mStr="\"";//引号的字符串
    QString str = mStr + key + mStr + ":" + mStr + value + mStr + ",";
    return str;
}

HMILotData MainWidgetFunction::getHMILotData()
{
    HMILotData lotFata;
    memset(&lotFata, 0, sizeof(HMILotData));

    memcpy(lotFata.HMIVerStr, getVersionStr().data(), getVersionStr().length());   // 版本信息
    memcpy(lotFata.fileName, m_fileName.data(), m_fileName.length());   // 文件名称

    u32 rackNum = g_pSettings->readFromIniFile("IOT/rackNumber").toInt();//机架号
    lotFata.machineNumber = rackNum;   // 机架号

    QString deliveryTime = g_pSettings->readFromIniFile("IOT/deliveryTime").toString();//工厂预计交货时间
    QByteArray arr = deliveryTime.toLocal8Bit();
    memcpy(lotFata.deliveryTime, arr.data(), arr.size());   //交货日期

    u16 debugProgress  =  g_pSettings->readFromIniFile("IOT/debugProgress").toInt();//调试进度
    lotFata.debugProgress = debugProgress;   //调试进度

    //电机总数-先固定写为4个，如果后续变动较大，可把电机个数写为全局变量或从其他cpp中传参
    lotFata.motorNum = 4;

    return lotFata;
}

//发送数据到物联网
void MainWidgetFunction::sendDataToGateway(s16 code,s16 type)
{
    QString mStr="\"";//引号的字符串

    QString mcType = mStr+U00016+mStr+":"+mStr+"Emb"+mStr+",";

    QString mcStr1;
    mcStr1.clear();
    QString mcStr2;
    mcStr2.clear();
    mcStr1 = mStr+"Towel"+mStr+":0,";
    mcStr2 = mStr+"Coil"+mStr+":0,";
    s16 towel = g_pSettings->readFromIniFile("HMI/towel").toInt();//是否有毛巾功能
    s16 coil = g_pSettings->readFromIniFile("HMI/coil").toInt();//是否有缠绕功能
    if(towel == 1)
    {
        mcStr1 = mStr+"Towel"+mStr+":1,";
    }
    if(coil == 1)
    {
        mcStr2 = mStr+"Coil"+mStr+":1,";
    }

    QString sensorMotorStr;
    sensorMotorStr.clear();

    sensorMotorStr = mStr+S00000+mStr+":1,"+mStr+S00010+mStr+":1,"+mStr+S00070+mStr+":1,"+mStr+S01000+mStr+":1,";

    if(type == 0)
    {
        switch (code)
        {
        case CSV_00_CODE_1:
            sensorMotorStr += mStr+S00020+mStr+":1,";
            sensorMotorStr += mStr+M0003+mStr+":1,";
            break;
        case CSV_00_CODE_4://边框检查
        case CSV_00_CODE_8://自动定软限位
            sensorMotorStr += mStr+S00200+mStr+":1,";
            sensorMotorStr += mStr+S00201+mStr+":1,";
            sensorMotorStr += mStr+S00220+mStr+":1,";
            sensorMotorStr += mStr+S00221+mStr+":1,";
            sensorMotorStr += mStr+S00230+mStr+":1,";
            sensorMotorStr += mStr+S00231+mStr+":1,";
            sensorMotorStr += mStr+M0001+mStr+":1,";
            sensorMotorStr += mStr+M0002+mStr+":1,";
            break;
        case CSV_00_CODE_5:
            sensorMotorStr += mStr+M0004+mStr+":1,";
            break;
        default:
            break;
        }
    }
    else if(type == CSV_MC_TYPE_02)
    {
        switch (code)
        {
        case CSV_02_CODE_1://毛巾M轴零位
            sensorMotorStr += mStr+S01020+mStr+":1,";
            sensorMotorStr += mStr+M0005+mStr+":1,";
            sensorMotorStr += mStr+M0006+mStr+":1,";
            break;
        case CSV_02_CODE_2://毛巾打环轴归零
            sensorMotorStr += mStr+S01021+mStr+":1,";
            sensorMotorStr += mStr+M0007+mStr+":1,";
            break;
        default:
            break;
        }
    }
    else if(type == CSV_MC_TYPE_03)
    {
        switch (code)
        {
        case CSV_03_CODE_1://缠绕压脚电机归零
            sensorMotorStr += mStr+M0008+mStr+":1,";
            sensorMotorStr += mStr+M0009+mStr+":1,";
            sensorMotorStr += mStr+M0010+mStr+":1,";
            break;
        case CSV_03_CODE_2://缠绕锯齿电机归零
            sensorMotorStr += mStr+M0011+mStr+":1,";
            break;
        default:
            break;
        }
    }

    int val = ((double)m_getScore / (double)m_totalScore) * 100;
    //emit siShowPercentage(val);//测试物联网用

    QString timeStr;
    timeStr.clear();

#ifdef Q_OS_LINUX
    timeStr = QString::number(QDateTime::currentDateTime().toMSecsSinceEpoch() - 28800000);//mcgs下时间差8个小时
#endif

#ifdef Q_OS_WIN
    timeStr = QString::number(QDateTime::currentDateTime().toMSecsSinceEpoch());
#endif

    QString lotStr;
    lotStr.clear();
    lotStr = "{" + mStr +  QString::number(m_HMILotData.machineNumber)  + "#" + mStr + ":[{" +
            mStr + "ts" + mStr + ":" + timeStr + "," +
            mStr + "values" + mStr + ":{\"timestamp" + mStr + ":" + timeStr + ",\"RackNumber\":\"" + QString::number(m_HMILotData.machineNumber)  + "#\"" + ","
            + mcType + mcStr1 + mcStr2 + sensorMotorStr;

    QString keyStr = compositionJson(U00001, QString::number(val));
    lotStr += keyStr;
    lotStr.chop(1);

    lotStr += "}}]}";
    //qDebug()<<lotStr;
    g_pLotMachine->sendLotDataToGateway(lotStr);
}

void MainWidgetFunction::setErrorCodeAndStateList(QList<ErrorCodeStateItem> list)
{
    m_errorCodeAndStateItemList.clear();
    m_errorCodeAndStateItemList.append(list);
}

//上电计算  关机时间  并发送给主控
void MainWidgetFunction::setShutDownTime()
{
    int oldSecond = g_pSettings->readFromIniFile("DateTime/second").toInt();//上次上电的系统时间

    QDateTime dateTime = QDateTime::currentDateTime();  //当前时间
    int curSecond = dateTime.toTime_t();//单位为秒        //新的时间
    int diff = curSecond - oldSecond;//关机秒数
    if (diff >= 0)
    {
    }
    else//小于0
    {
        diff = 5000*3600;
    }
    qDebug()<<"shutdown second"<<diff;

    if(g_pMachine != NULL && oldSecond != 0)
    {
        g_pMachine->setShutDownTime(0, diff);//可能这个diff太大了
    }
}
//设置机器状态
void MainWidgetFunction::setMcStates(MCStatus mcStatus)
{
    memset((char*)&m_mcStatus,0,sizeof(MCStatus));
    memcpy((char*)&m_mcStatus,(char*)&mcStatus,sizeof(MCStatus));
}

QString MainWidgetFunction::getVersionStr()
{
    QString str;
    str.sprintf("RPQC-ALL-XPlatformQ-LAUTO-V");
    str += getCompileDateTime();
    return str;
}

//将定位点或起绣点写回到文件中
void MainWidgetFunction::writePonitToFile(QString filePath,int x, int y, int flag)
{
    QFileInfo fileInfo(filePath);
    QString suffix = fileInfo.suffix().toUpper();//后缀大写

    if(suffix == "DST")
    {
        DataFileDst dst;
        dst.initFile(filePath);
        dst.loadFile();
        dst.writePointToFile(x,y,flag);
    }
    else if(suffix == "DSR")
    {
        DataFileDsr dsr;
        dsr.initFile(filePath);
        dsr.loadFile();
        dsr.writePointToFile(x,y,flag);
    }
    else if(suffix == "QUI")
    {
    }
    else if(suffix == "QUIX")
    {
    }
    else if(suffix == "PLT")
    {
    }
    else if(suffix == "DXF")
    {
    }
}

//机器信息改变
void MainWidgetFunction::slotMCInfoChange()
{
    static int fID = 0;
    m_mcStatus = g_pMachine->getMcStatus();

    //可使用时长
    int workTime = m_mcStatus.workableTimer;
    if( workTime > 0 && workTime < INT_MAX )
    {
        QString strTime;
        QString strDay;
        QString strHour;
        QString strSec;

        int day = workTime/(60 *24);

        //使用时长不足5天就主动提示用户
        if(day < 5 && fID == 0)
        {
            m_pPromptDlg->initDialog(PromptDialog::BTN_OK);
            m_pPromptDlg->setTitleStr(tr("Prompt"));

            QString str;

            strDay  = QString::number(workTime/(60 *24) , 10);
            strHour = QString::number((workTime%(60 *24))/60 , 10) ;
            strSec  = QString::number(workTime%60 , 10);

            strTime = strDay + " " + tr("Day") + " " + strHour + " " + tr("Hour")  + " " +  strSec  + " " + tr("Minutes") ;  // 天   小时   分钟

            //机器剩余可用时间为
            str = tr("The remaining available time of the machine is ") + strTime;

            m_pPromptDlg->setContentStr(str);
            m_pPromptDlg->exec();
            //开启一个定时器，隔4个小时就发一次查询机器状态
            m_pTipsTimer->start();
            fID++;
        }
    }
}

//给主控发查询机器信息
void MainWidgetFunction::onTipsTimer()
{
    if (g_pMachine != NULL)
    {
        g_pMachine->getInfoFromMachine();
    }
    m_pTipsTimer->stop(); //关定时器
}

void MainWidgetFunction::slotSetDynamicIP(QString ssid)
{
    if(ssid.length() <= 0)
    {
        m_pPromptDlg->initDialog(PromptDialog::BTN_OK);
        m_pPromptDlg->setTitleStr(tr("Prompt"));
        m_pPromptDlg->setContentStr(tr("ssid is empty!"));//ssid为空！
        m_pPromptDlg->exec();
        return;
    }

    WordsInputDialog wordInputDlg;
    wordInputDlg.wifiClean();
    wordInputDlg.setTitleStr(tr("Password input"));//密码输入
    wordInputDlg.setOldWordsStr("");
    if(wordInputDlg.exec() == 1)
    {
#ifdef Q_OS_LINUX
        QString psd = wordInputDlg.getInputStr();
        //base64解密
        //向配置文件写入加密结果，设置动态IP
        QString iniPath = WIFIINIPATH;
        QSettings setting(iniPath,QSettings::IniFormat);
        setting.beginGroup("WIFI");
        setting.setValue("default_passwd",psd.toLatin1().toBase64());
        setting.setValue("default_ssid",ssid.toLatin1().toBase64());
        setting.setValue("static_ip","");
        setting.setValue("static_mask","");
        setting.setValue("static_mode","false");
        setting.endGroup();

        system("sync");

        m_pPromptDlg->initDialog(PromptDialog::BTN_OK_CANCEL);
        m_pPromptDlg->setTitleStr(tr("Prompt"));

        QString str;
        str = tr("Settings require screen restart to take effect!");//设置需要重启屏幕才生效!
        m_pPromptDlg->setContentStr(str);
        if(m_pPromptDlg->exec() == 1)
        {
            system("reboot");
        }
#endif
    }
}

void MainWidgetFunction::slotSetStaticIP(QString ssid, QString psd,QString dnip)
{
    if(ssid.length() <= 0)
    {
        m_pPromptDlg->initDialog(PromptDialog::BTN_OK);
        m_pPromptDlg->setTitleStr(tr("Prompt"));
        m_pPromptDlg->setContentStr(tr("ssid is empty!"));//ssid为空！
        m_pPromptDlg->exec();
        return;
    }
    if(psd.length() <= 0){}//为了去掉编译警告

    PassWordDialog passWordDlg;
    QString ip;
    ip.clear();
    passWordDlg.setTitleStr(tr("IP input"),-1);//IP输入
    passWordDlg.setShowIfVisible(true);
    passWordDlg.setIpStr(dnip);
    int rslt = passWordDlg.exec();
    if(rslt == 1)
    {
        ip = passWordDlg.getInputStr();
    }

#ifdef Q_OS_LINUX
    if(ip.length() <= 0)
    {
        return;
    }

    //base64解密
    //向配置文件写入加密结果，设置静态IP
    QString iniPath = WIFIINIPATH;
    QSettings setting(iniPath,QSettings::IniFormat);
    setting.beginGroup("WIFI");
    setting.setValue("default_passwd",psd.toLatin1().toBase64());
    setting.setValue("default_ssid",ssid.toLatin1().toBase64());
    setting.setValue("static_ip",ip);
    setting.setValue("static_mask","255.255.255.0");
    setting.setValue("static_mode","true");
    setting.endGroup();

    system("sync");

    m_pPromptDlg->initDialog(PromptDialog::BTN_OK_CANCEL);
    m_pPromptDlg->setTitleStr(tr("Prompt"));

    QString str;
    str = tr("Settings require screen restart to take effect!");//设置需要重启屏幕才生效!
    m_pPromptDlg->setContentStr(str);
    if(m_pPromptDlg->exec() == 1)
    {
        system("reboot");
    }
    return;

#endif
}

void MainWidgetFunction::slotSpindleAction(int action)
{
    if(g_pMachine != NULL)
    {
        g_pMachine->motoMove(MT_LM, action, 0);
    }
}

void MainWidgetFunction::slotSpindleRotate(int angle)
{
    if(g_pMachine != NULL)
    {
        if(g_emMacType ==  MACHINE_THICK_WIRING)
        {
            g_pMachine->manualAction(MS_TO_ANGLE,angle);
        }
        else
        {
            g_pMachine->manualAction(MT_LM,angle);
        }
    }
}

void MainWidgetFunction::slotRotateRotate(int angle)
{
    if(g_pMachine != NULL)
    {
        if(g_emMacType ==  MACHINE_THICK_WIRING)
        {
            g_pMachine->manualAction(ROT_TO_ANGLE,angle);
        }
        else
        {
            g_pMachine->manualAction(MT_LRR,angle);
        }
    }
}

void MainWidgetFunction::slotAutoPull(int length)
{
    if(g_pMachine != NULL)
    {
        if(g_emMacType ==  MACHINE_THICK_WIRING)
        {
            g_pMachine->manualAction(AUTO_PULL,length);
        }
    }
}

void MainWidgetFunction::slotSpindleResearch(int spindleTime , int spindleSpeed)
{
    if(g_pMachine != NULL)
    {
        if(g_emMacType ==  MACHINE_THICK_WIRING)
        {
            g_pMachine->manualAction(WIRE_MS_RUN,spindleTime,spindleSpeed);
        }
    }
}

//接收到主板的物联网数据
void MainWidgetFunction::slotReceiveLotData()
{
    static int nID = 0;

    //因为串口模式打开串口成功在连接的信号和槽之前，所以写以下代码表示刚建立连接就向网关发送连接符
    //网口连接方式不会有此问题，串口转wifi又不能检测wifi断开，所以每次都发送连接符
    QString mStr="\"";//引号的字符串
    QString lotStr;
    lotStr.clear();
    if(nID % 2 == 0)//为了让两条间隔分开，用取余做判断，否则网关收到键值对错误
    {
        lotStr += "{" + mStr + "device" + mStr + ":" + mStr + QString::number(m_HMILotData.machineNumber) + "#" + mStr + "}";
        //如果物联网Machine  不是空
        if(g_pLotMachine != NULL)
        {
            //相当于Machine给主板发数据
            g_pLotMachine->sendLotDataToGateway(lotStr);//发送物联数据（机器编号）到网关
        }
        nID++;
        return;
    }

    //emit siReceiveLotDat();   //测试物联网用
    //qDebug()<<"slotReceiveLotData";   //测试物联网用

    McLotData nMcLotData = g_pMachine->getMcLotData();//得到下位机的物联网数据
    HMILotData nHMILotData = getHMILotData(); //得到界面要发给网关的物联网数据

    QString timeStr;
    timeStr.clear();

#ifdef Q_OS_LINUX
    timeStr = QString::number(QDateTime::currentDateTime().toMSecsSinceEpoch() - 28800000);//mcgs下时间差8个小时
#endif

#ifdef Q_OS_WIN
    timeStr = QString::number(QDateTime::currentDateTime().toMSecsSinceEpoch());
#endif

    lotStr.clear();
    lotStr = "{" + mStr +  QString::number(m_HMILotData.machineNumber)  + "#" + mStr + ":[{" +
            mStr + "ts" + mStr + ":" + timeStr + "," +
            mStr + "values" + mStr + ":{\"timestamp" + mStr + ":" + timeStr + ",\"RackNumber\":\"" + QString::number(m_HMILotData.machineNumber)  + "#\"" + ",";

    QString keyStr;
    keyStr.clear();

    if(g_pLotMachine != NULL)
    {
        if(nID == 0)
        {
            keyStr = compositionJson(U00033, S0504);
        }
        else
        {
            if ((m_mcStatus.workStatus & WORK_STA_BUSY) != 0)    // 下位机在执行动作
            {
                keyStr = compositionJson(U00033, S0505);
            }
            else
            {
                keyStr = compositionJson(U00033, S0504);
            }
        }
        lotStr += keyStr;

        //机器版本
        //                    界面上存的下位机数据        下位机里的数据
        if(memcmp(&m_mcLotData.mBoardVerStr, &nMcLotData.mBoardVerStr, sizeof(nMcLotData.mBoardVerStr)) != 0)
        {
            keyStr = compositionJson(U00022, QString::fromLocal8Bit(nMcLotData.mBoardVerStr));
            lotStr += keyStr;
        }

        //报警信息
        // 界面上存的下位机数据    不等于    下位机里的数据
        //这种情况应该就是主控里的数据和界面上存的不一样了
        if(m_mcLotData.errorCode != nMcLotData.errorCode)
        {
            if ((nMcLotData.errorCode > 0 && nMcLotData.errorCode < 0x100) || nMcLotData.errorCode > 0x200)
            {
                QString info;
                info.clear();
                info = getErrStr(nMcLotData.errorCode);
                //如果不是通用错误(即info为空)，就从机型cpp中的错误代码查找
                if(info.length() <= 0)
                {
                    for(int i = 0; i < m_errorCodeAndStateItemList.size(); i++)
                    {
                        if(nMcLotData.errorCode == m_errorCodeAndStateItemList[i].m_code)
                        {
                            info = m_errorCodeAndStateItemList[i].m_name;
                            break;
                        }
                    }
                }
                //如果不是通用错误也不是机型cpp中的错误代码，就显示未定义错误
                if(info.length() <= 0)
                {
                    QString errorCode;
                    errorCode.sprintf("CODE 0x%x", nMcLotData.errorCode);
                    info.append(tr("Undefined error,") + errorCode);//未定义错误,
                }

                keyStr = compositionJson(U00023, QString::number(nMcLotData.errorCode));// 原来为info,lxs修改
                lotStr += keyStr;
            }
        }

        //授权剩余时间(min)
        if(m_mcLotData.workableTimer != nMcLotData.workableTimer)
        {
            keyStr = compositionJson(U00025, QString::number(nMcLotData.workableTimer));
            lotStr += keyStr;
        }

        //开机时间(min)
        if(m_mcLotData.bootTimer != nMcLotData.bootTimer)
        {
            keyStr = compositionJson(U00026, QString::number(nMcLotData.bootTimer));
            lotStr += keyStr;
        }

        //工作时间(min)
        if(m_mcLotData.workTimer != nMcLotData.workTimer)
        {
            keyStr = compositionJson(U00027, QString::number(nMcLotData.workTimer));
            lotStr += keyStr;
        }

        //工作转速
        if(m_mcLotData.workRpm != nMcLotData.workRpm)
        {
            keyStr = compositionJson(U00004, QString::number(nMcLotData.workRpm));
            lotStr += keyStr;
        }

        //当前产量
        if(m_mcLotData.curOutCounter != nMcLotData.curOutCounter)
        {
            keyStr = compositionJson(U00028, QString::number(nMcLotData.curOutCounter));
            lotStr += keyStr;
        }

        //累计产量
        if(m_mcLotData.totalOutCounter != nMcLotData.totalOutCounter)
        {
            keyStr = compositionJson(U00014, QString::number(nMcLotData.totalOutCounter));
            lotStr += keyStr;
        }

        //产量设定
        if(m_mcLotData.expectedOutput != nMcLotData.expectedOutput)
        {
            keyStr = compositionJson(U00029, QString::number(nMcLotData.expectedOutput));
            lotStr += keyStr;
        }

        //设备(机器)ID
        if(memcmp(&m_mcLotData.boardId, &nMcLotData.boardId, sizeof(nMcLotData.boardId)) != 0)
        {
            keyStr = compositionJson(U00017, QString::fromLocal8Bit(nMcLotData.boardId));
            lotStr += keyStr;
        }

        //主轴零位
        if(m_mcLotData.spindleZeroSta != nMcLotData.spindleZeroSta)
        {
            keyStr = compositionJson(U00034, QString::number(nMcLotData.spindleZeroSta));
            lotStr += keyStr;
        }

        //主轴角度
        if(m_mcLotData.spindleAngle != nMcLotData.spindleAngle)
        {
            keyStr = compositionJson(U00035, QString::number(nMcLotData.spindleAngle));
            lotStr += keyStr;
        }

        //电机1坐标(绣框X坐标)
        if(m_mcLotData.motosPos[1] != nMcLotData.motosPos[1])
        {
            keyStr = compositionJson(U00036, QString::number(nMcLotData.motosPos[1]));
            lotStr += keyStr;
        }

        //电机2坐标(绣框Y坐标)
        if(m_mcLotData.motosPos[2] != nMcLotData.motosPos[2])
        {
            keyStr = compositionJson(U00037, QString::number(nMcLotData.motosPos[2]));
            lotStr += keyStr;
        }

        //8对应m_mcLotData.sensorSignal的数量
        s16 sensorNum = 0;
        for(int i = 0; i < 8; i++)
        {
            for(int j = 0; j < 32; j++)//一个u32是32位
            {
                if(((m_mcLotData.sensorSignal[i] >> j) & 1) != ((nMcLotData.sensorSignal[i] >> j) & 1))
                {
                    QString sensorName;
                    sensorName.clear();
                    switch (i*32+j)
                    {
                    case 0:sensorName = U00038;break;//启动按钮1
                    case 1:sensorName = U00039;break;//暂停按钮1
                    case 2:sensorName = U00040;break;//点动按钮1
                    case 3:sensorName = U00041;break;//主框架X零位
                    case 4:sensorName = U00042;break;//主框架Y零位
                    case 5:sensorName = U00043;break;//主框架X负限位
                    case 6:sensorName = U00044;break;//主框架Y负限位
                    case 7:sensorName = U00045;break;//主框架X正限位
                    case 8:sensorName = U00046;break;//主框架Y正限位
                    case 9:sensorName = U00047;break;//剪刀回位
                    default:sensorName.clear();break;
                    }

                    if(sensorName.length() > 0)
                    {
                        keyStr = compositionJson(sensorName, QString::number((nMcLotData.sensorSignal[i] >> j) & 1));
                        lotStr += keyStr;
                        sensorNum++;
                    }
                }
            }
        }
        //传感器总数
        keyStr = compositionJson(U000103, QString::number(nMcLotData.sensonNumbers));//原为Qstring::number(sensorNum)
        lotStr += keyStr;

        //  机器配置
        //        if(m_mcLotData.machinecfg != nMcLotData.machinecfg)
        //        {

        //                keyStr = compositionJson(U000120, QString::number((nMcLotData.machinecfg >> 0) & 1)+ "#");//勾线模式
        //                lotStr += keyStr;

        //                keyStr = compositionJson(U000121, QString::number((nMcLotData.machinecfg >>1) & 1)+ "#");//锁头模式
        //                lotStr += keyStr;

        //        }

        //  缝纫机头个数
        if(m_mcLotData.sewHeadNumbers != nMcLotData.sewHeadNumbers)
        {
            keyStr = compositionJson(U000122, QString::number(nMcLotData.sewHeadNumbers)+ "#");
            lotStr += keyStr;
        }

        //  绣花机头个数
        if(m_mcLotData.embHeadNumbers != nMcLotData.embHeadNumbers)
        {
            keyStr = compositionJson(U000123, QString::number(nMcLotData.embHeadNumbers));
            lotStr += keyStr;
        }

        //绣花机针个数
        if(m_mcLotData.embneedleNumbers != nMcLotData.embneedleNumbers)
        {
            keyStr = compositionJson(U000124, QString::number(nMcLotData.embneedleNumbers));
            lotStr += keyStr;
        }
        //冲孔机头个数
        if(m_mcLotData.punchHeadNumbers != nMcLotData.punchHeadNumbers)
        {
            keyStr = compositionJson(U000125, QString::number(nMcLotData.punchHeadNumbers));
            lotStr += keyStr;
        }
        //冲孔机针个数
        if(m_mcLotData.punchneedleNumbers != nMcLotData.punchneedleNumbers)
        {
            keyStr = compositionJson(U000126, QString::number(nMcLotData.punchneedleNumbers));
            lotStr += keyStr;
        }

        //界面版本
        //memcmp(s1,s2,n)就是比较s1和s2的前n个字节的ascII码值
        if(memcmp(&m_HMILotData.HMIVerStr, &nHMILotData.HMIVerStr, sizeof(nHMILotData.HMIVerStr)) != 0)
        {
            keyStr = compositionJson(U00030, QString::fromLocal8Bit(nHMILotData.HMIVerStr));
            lotStr += keyStr;
        }

        //机架号
        if(m_HMILotData.machineNumber != nHMILotData.machineNumber)
        {
            keyStr = compositionJson(U00018, QString::number(nHMILotData.machineNumber) + "#");
            lotStr += keyStr;
        }

        //电机总数
        //界面上存的电机数      不等于    界面上存的电机数  的时候就往下发数据
        if(m_HMILotData.motorNum != nHMILotData.motorNum)
        {
            keyStr = compositionJson(U000102, QString::number(nHMILotData.motorNum));
            lotStr += keyStr;
        }
        //调试进度
        if(m_HMILotData.debugProgress != nHMILotData.debugProgress)
        {
            keyStr = compositionJson(U000119, QString::number(nHMILotData.debugProgress));
            lotStr += keyStr;
        }
        //交付日期
        if(memcmp(&m_HMILotData.deliveryTime, &nHMILotData.deliveryTime, sizeof(nHMILotData.deliveryTime)) != 0)
        {
            keyStr = compositionJson(U000118, QString::fromLocal8Bit(nHMILotData.deliveryTime));
            lotStr += keyStr;
        }
        //       workProgress = ;
        //        //机器工作进度  -rq
        //        if(m_HMILotData.workProgress != nHMILotData.workProgress)
        //        {
        //            keyStr = compositionJson(U000118, QString::numbert(nHMILotData.workProgress));
        //            lotStr += keyStr;
        //        }
#if(0)
        //当前加工文件名称
        if(memcmp(&m_HMILotData.fileName, &nHMILotData.fileName, sizeof(nHMILotData.fileName)) != 0)
        {
            keyStr = compositionJson(U00031, QString::fromLocal8Bit(nHMILotData.fileName));
            lotStr += keyStr;
        }
#endif

        if(lotStr.at(lotStr.length()-1) == ',')//去除最后一个逗号
        {
            lotStr.chop(1); //删除字符串右边n个字符
        }
        lotStr += "}}]}";
        //qDebug()<<lotStr;
        //发送物联数据到网关
        g_pLotMachine->sendLotDataToGateway(lotStr);
    }

    m_mcLotData = nMcLotData;
    m_HMILotData = nHMILotData;
    nID++;
    qDebug()<<nHMILotData.deliveryTime;

}

//执行网关数据动作
void MainWidgetFunction::slotRunLotDataAction(QString str)
{
    int cmd = str.toInt();
    if(cmd == 1)//点动
    {
        funSpindleJog();
    }
    else if(cmd == 2)//剪线
    {
        funManualTrim();
    }
}

void MainWidgetFunction::slotTransProgress(u8 fileType, int send, int total)
{
    int csend = 0;
    int ctotal = 0;

    if(fileType == FILE_TYPE_PGM)//主控升级文件
    {
        csend += g_pMachine->getTotalSendNum();
        ctotal += g_pMachine->getTotalPacketNum();

        if (csend < 0 && ctotal < 0)
        {
            // 失败
            m_pPromptDlg->initDialog(PromptDialog::BTN_UCANCEL);
            m_pPromptDlg->setTitleStr(tr("MC Upgrade"));//主控升级
            //m_pPromptDlg->setButtonUCancelStr(tr("Close"));//关闭
            m_pPromptDlg->setContentProcessStr(tr("Failed to upgrade the main control system!")); //主控系统升级失败!
        }
        else if (csend == 0 && ctotal == 0)
        {
            // 成功
            m_pPromptDlg->initDialog(PromptDialog::BTN_RESTART);
            m_pPromptDlg->setTitleStr(tr("MC Upgrade"));//主控升级
            m_pPromptDlg->setContentProcessStr(tr("The main control system has been successed, waiting until machine restart"));
            int seconds = 10;//界面重启时间改成10秒
            for(int i = 0; i < seconds; i++)
            {
                QString str = QString(tr("System will restart %1 s later")).arg(seconds-i);//系统将在 %1 秒后重启
                m_pPromptDlg->setContentProcessStr(str);
                g_pMachine->sleep(1);
            }

#ifdef Q_OS_WIN
            qApp->exit();
#endif

#ifdef Q_OS_LINUX
            system("reboot");
#endif

            m_pPromptDlg->hide();
        }
        else if(csend >= 0 && csend <= ctotal)
        {
            m_pPromptDlg->initDialog(PromptDialog::BTN_UCANCEL);
            m_pPromptDlg->setTitleStr(tr("MC Upgrade"));//主控升级
            m_pPromptDlg->setContentProcessStr(tr("Main control system is being upgraded..."));  //主控系统升级中...
            //m_pPromptDlg->setButtonUCancelStr(tr("Cancel"));//取消
            m_pPromptDlg->setRange(0, total);
            m_pPromptDlg->setValue(send);
            m_pPromptDlg->show();
            QCoreApplication::processEvents(QEventLoop::AllEvents);
        }
        else
        {
            m_pPromptDlg->hide();
        }
    }
    else
    {
        if (send < 0 && total < 0)
        {
            // 失败
            m_pPromptDlg->initDialog(PromptDialog::BTN_UCANCEL);

            if(fileType == FILE_TYPE_DAT)//花样数据文件(边框刺绣文件)
            {
                m_pPromptDlg->setTitleStr(tr("Prompt"));
                //m_pPromptDlg->setButtonUCancelStr(tr("Close"));//关闭
                m_pPromptDlg->setContentStr(tr("Failed to send data file!"));  //发送数据文件失败!
            }
        }
        else if (send == 0 && total == 0)
        {
            if(fileType == FILE_TYPE_DAT)//花样数据文件
            {
                // 成功
                m_pPromptDlg->initDialog(PromptDialog::BTN_OK);
                m_pPromptDlg->setTitleStr(tr("Prompt"));//主控升级
                m_pPromptDlg->setContentProcessStr(tr("The data file is send successfully!")); //数据文件发送成功!
            }
            m_pPromptDlg->hide();
        }
        else if(send >= 0 && send <= total)
        {
            m_pPromptDlg->initDialog(PromptDialog::BTN_UCANCEL);
            if(fileType == FILE_TYPE_DAT)//花样数据文件
            {
                m_pPromptDlg->setTitleStr(tr("Prompt"));
                m_pPromptDlg->setContentProcessStr(tr("Data file sending..."));  //数据文件发送中...
            }
            //m_pPromptDlg->setButtonUCancelStr(tr("Cancel"));//取消
            m_pPromptDlg->setRange(0, total);
            m_pPromptDlg->setValue(send);
            m_pPromptDlg->show();
            QCoreApplication::processEvents(QEventLoop::AllEvents);
        }
        else
        {
            m_pPromptDlg->hide();
        }
    }
}

//导出csv文件到U盘
void MainWidgetFunction::slotCsvExport(int logType)
{
    QString usbPath = detectUsb();//U盘路径
    if(usbPath.length() <= 0)
    {
        //优盘不存在
        m_pPromptDlg->initDialog(PromptDialog::BTN_OK);
        m_pPromptDlg->setTitleStr(tr("Prompt"));

        QString str;
        str = tr("USB flash drive is not detected!");//未检测到优盘！
        m_pPromptDlg->setContentStr(str);
        m_pPromptDlg->exec();
        return;
    }

    QDir apppath(qApp->applicationDirPath());//D:/work/workQT/XPlatform/Windows/debug
    QString newName = usbPath + apppath.separator();//G
    QString timeStr = QDateTime::currentDateTime().toString("_yyMMdd_hhmmss");//时间日期  _230215_144121

    QString astr;
    if(logType == TYPE_ERROR)
    {
        astr = "error";
    }
    else if(logType == TYPE_BREAK)
    {
        astr = "break";
    }
    else if(logType == TYPE_DEBUGINFO)
    {
        astr = "debuginfo";
    }

    QString newFileName = newName+astr+timeStr+".csv";

    //csv文件路径
    QString csvfile;
    if(logType == TYPE_ERROR)
    {
        csvfile = apppath.path() + apppath.separator() + CSV_ERROR;
    }
    else if(logType == TYPE_BREAK)
    {
        csvfile = apppath.path() + apppath.separator() + CSV_BREAK;
    }
    else if(logType == TYPE_DEBUGINFO)
    {
        csvfile = apppath.path() + apppath.separator() + CSV_DEBUGINFO;
    }
    QString csvfilePath = QDir(csvfile).absolutePath();//为了将"\"变为"/"
    bool bl = QFile::copy(csvfilePath,newFileName);

    //强制写入
    //linux下写入文件或者拷贝、删除文件的情况
#ifdef Q_OS_LINUX
    system("sync");
#endif

    QString str;
    if(bl == true)
    {
        str = tr("Journal exported successfully!");//文件日志导出成功！
    }
    else
    {
        str = tr("Journal exported failed!");//文件日志导出失败！
    }

    m_pPromptDlg->initDialog(PromptDialog::BTN_OK);
    m_pPromptDlg->setTitleStr(tr("Prompt"));

    m_pPromptDlg->setContentStr(str);
    m_pPromptDlg->exec();
    return;
}

void MainWidgetFunction::slotClearJournal()
{
    QDir apppath(qApp->applicationDirPath());
    QString csvfile = apppath.path() + apppath.separator();
    g_pSettings->fileClear(csvfile+CSV_ERROR);//清空文件日志内容，但文件还在
    g_pSettings->fileClear(csvfile+CSV_BREAK);//清空文件日志内容，但文件还在

    // 刷新文件日志界面信息
    m_pSystemManageDlg->initDialog();
    m_pSystemManageDlg->exec(JOURNAL);//显示窗体
}

void MainWidgetFunction::slotRefreshWifiList()
{
    QStringList wifiStrList;
    wifiStrList.clear();
    s16 rel = refreshWifiList(wifiStrList,1);
    if(rel > 0)
    {
        m_pSystemManageDlg->setItemList(wifiStrList);
    }
}

//清空产量统计
void MainWidgetFunction::slotClearProductStatis()
{
    if(g_pMachine != NULL)
    {
        g_pMachine->resetOutput();//清除产量统计(主控计数)
    }

    emit siClearPatternBreakLineNum();

    addProductStatisInfo(0);//花版断线次数清零
    m_pSystemManageDlg->refreshUi();
}

//用户登录
void MainWidgetFunction::slotUserLogin(s16 user)
{
    // QTextCodec *cod = QTextCodec::codecForLocale();
    PassWordDialog passWordDlg;
    QString str("");
    if(user == repair)
    {
        passWordDlg.setTitleStr(tr("Password input *"));//密码输入
    }
    else if(user == root)
    {
        passWordDlg.setTitleStr(tr("Password input **"));//密码输入
    }
    else if(user == resetpara)
    {
        passWordDlg.setTitleStr(tr("Password input ****"));//密码输入
    }
    int rslt = passWordDlg.exec();
    if(rslt == 1)
    {
        str = passWordDlg.getInputStr();

        if(user == repair)
        {
            if (str == PASSWORD_ONE)
            {
                g_emUser = repair;
                emit siSetButtonUserLogo(1);
            }
            else
            {
                m_pPromptDlg->initDialog(PromptDialog::BTN_OK);
                m_pPromptDlg->setTitleStr(tr("Prompt"));
                m_pPromptDlg->setContentStr(tr("The password is wrong,please re-enter!"));//密码错误，请重新输入密码!
                m_pPromptDlg->exec();
                return;
            }
        }
        else if(user == root)
        {
            if (str == PASSWORD_TWO)
            {
                g_emUser = root;
                emit siSetButtonUserLogo(2);
            }
            else
            {
                m_pPromptDlg->initDialog(PromptDialog::BTN_OK);
                m_pPromptDlg->setTitleStr(tr("Prompt"));
                m_pPromptDlg->setContentStr(tr("The password is wrong,please re-enter!"));//密码错误，请重新输入密码!
                m_pPromptDlg->exec();
                return;
            }
        }
        else if(user == resetpara)
        {
            if (str == PASSWORD_RESETPARA)
            {
                m_pPromptDlg->initDialog(PromptDialog::BTN_OK);
                m_pPromptDlg->setTitleStr(tr("Prompt"));
                g_emUser = resetpara;
                m_pPromptDlg->setContentStr(tr("reset parameters password successfully logged in!"));//重置参数密码成功登入!
                m_pPromptDlg->exec();
                emit siSetButtonUserLogo(2);
            }
            else
            {
                m_pPromptDlg->initDialog(PromptDialog::BTN_OK);
                m_pPromptDlg->setTitleStr(tr("Prompt"));
                m_pPromptDlg->setContentStr(tr("The password is wrong,please re-enter!"));//密码错误，请重新输入密码!
                m_pPromptDlg->exec();
                return;
            }


        }
    }
}

//界面解密
void MainWidgetFunction::slotHMIDecrypt(QString id)
{
    // 获取网卡号并输入序列号
    m_pPromptDlg->initDialog(PromptDialog::BTN_HMI_DECRYPT);
    m_pPromptDlg->setTitleStr(tr("HMI decrypt"));
    m_pPromptDlg->setContentHMIDecryptShow(id);
    if(m_pPromptDlg->exec() == 1)
    {
        QString inputStr = m_pPromptDlg->getInputPassword();
        QByteArray inputAry = inputStr.toLatin1();

        QString idStr = m_pPromptDlg->getNetworkCardID();
        QByteArray idAry = idStr.toLatin1();

        char inputBuf[20];       //输入的注册码
        u8 idBuf[12];                //id号16进制字符串
        memset(inputBuf,0,sizeof(inputBuf));
        memset(idBuf,0,sizeof(idBuf));
        memcpy(inputBuf,inputAry.data(),inputStr.toLatin1().length());
        memcpy(idBuf,idAry.data(),idStr.toLatin1().length());

        char outputBuf[20];    //生成的注册码
        int num,i;
        u8 anBuf[16],chanBuf[16];
        memset(anBuf,0,sizeof(anBuf));
        memset(chanBuf,0,sizeof(chanBuf));
        memset(outputBuf,0,sizeof(outputBuf));
        for(i = 0; i < 4; i++)
        {
            if((inputBuf[i] >= '0') && (inputBuf[i] <= '9'))
                anBuf[i]=inputBuf[i] - '0';
            else if((inputBuf[i] >= 'a') && (inputBuf[i] <= 'f'))
                anBuf[i]=inputBuf[i] - 'a' + 10;
            else if((inputBuf[i] >= 'A') && (inputBuf[i] <= 'F'))
                anBuf[i]=inputBuf[i] - 'A' + 10;
            else
                break;
        }

        for(u16 i = 0; i < sizeof(idBuf);)
        {
            if((idBuf[i] >= '0') && (idBuf[i] <= '9'))
                idBuf[i]=idBuf[i] - '0';
            else if((idBuf[i] >= 'a') && (idBuf[i] <= 'f'))
                idBuf[i]=idBuf[i] - 'a' + 10;
            else if((idBuf[i] >= 'A') && (idBuf[i] <= 'F'))
                idBuf[i]=idBuf[i] - 'A' + 10;

            if((idBuf[i+1] >= '0') && (idBuf[i+1] <= '9'))
                idBuf[i+1]=idBuf[i+1] - '0';
            else if((idBuf[i+1] >= 'a') && (idBuf[i+1] <= 'f'))
                idBuf[i+1]=idBuf[i+1] - 'a' + 10;
            else if((idBuf[i+1] >= 'A') && (idBuf[i+1] <= 'F'))
                idBuf[i+1]=idBuf[i+1] - 'A' + 10;

            i += 2;
        }

        num=((u8)(anBuf[0]*16 + anBuf[1]))*256 + (u8)(anBuf[2]*16 + anBuf[3]);
        anBuf[4]=(u8)(((idBuf[0] << 4) | idBuf[1]) + num) >> 4;
        anBuf[5]=(u8)(((idBuf[0] << 4) | idBuf[1]) + num) & 0x0f;
        anBuf[6]=(u8)(((idBuf[2] << 4) | idBuf[3]) + num) >> 4;
        anBuf[7]=(u8)(((idBuf[2] << 4) | idBuf[3]) + num) & 0x0f;
        anBuf[8]=(u8)(((idBuf[4] << 4) | idBuf[5]) + num) >> 4;
        anBuf[9]=(u8)(((idBuf[4] << 4) | idBuf[5]) + num) & 0x0f;
        anBuf[10]=(u8)(((idBuf[6] << 4) | idBuf[7]) + num) >> 4;
        anBuf[11]=(u8)(((idBuf[6] << 4) | idBuf[7]) + num) & 0x0f;
        anBuf[12]=(u8)(((idBuf[8] << 4) | idBuf[9]) + num) >> 4;
        anBuf[13]=(u8)(((idBuf[8] << 4) | idBuf[9]) + num) & 0x0f;
        anBuf[14]=(u8)(((idBuf[10] << 4) | idBuf[11]) + num) >> 4;
        anBuf[15]=(u8)(((idBuf[10] << 4) | idBuf[11]) + num) & 0x0f;

        chanBuf[0]=(u8)(anBuf[0]*16 + anBuf[1]);
        chanBuf[1]=(u8)(anBuf[2]*16 + anBuf[3]);
        chanBuf[2]=(u8)(anBuf[7]*16 + anBuf[9]);
        chanBuf[3]=(u8)(anBuf[6]*16 + anBuf[8]);
        chanBuf[4]=(u8)(anBuf[10]*16 + anBuf[15]);
        chanBuf[5]=(u8)(anBuf[5]*16 + anBuf[11]);
        chanBuf[6]=(u8)(anBuf[13]*16 + anBuf[4]);
        chanBuf[7]=(u8)(anBuf[14]*16 + anBuf[12]);

        //id号长度大于12，以此类推
        //chanbuf[8]=(u8)(anbuf[17]*16 + anbuf[16]);
        //chanbuf[9]=(u8)(anbuf[19]*16 + anbuf[18]);
        //chanbuf[10]=(u8)(anbuf[21]*16 + anbuf[20]);
        sprintf(outputBuf,"%02x%02x%02x%02x%02x%02x%02x%02x",chanBuf[0],
                chanBuf[1],chanBuf[2],chanBuf[3],chanBuf[4],chanBuf[5],chanBuf[6],chanBuf[7]);

        QDir apppath(qApp->applicationDirPath());
        QString HMIDecryptConfigfile;
        HMIDecryptConfigfile = apppath.path() + apppath.separator() + "HMIDecryptConfig.ini";
        QSettings iniSetting(HMIDecryptConfigfile, QSettings::IniFormat);

        if( 0 == memcmp(inputBuf, outputBuf, sizeof(inputBuf)) ) // 比较两个缓存区内容是否相同(等于0相等)
        {
            m_pPromptDlg->initDialog(PromptDialog::BTN_OK);
            m_pPromptDlg->setTitleStr(tr("Prompt"));

            QString str;
            str = tr("The interface program is licensed, and then take effect after restarting, please restart manually!");//界面程序授权成功,重启后生效,请手动重启!
            m_pPromptDlg->setContentStr(str);
            m_pPromptDlg->exec();

            iniSetting.setValue("HMIDecrypt/ifdecrypt",1);

            return;
        }
        else
        {
            m_pPromptDlg->initDialog(PromptDialog::BTN_OK);
            m_pPromptDlg->setTitleStr(tr("Prompt"));

            QString str;
            str = tr("Password error, interface program authorization failed!");//密码错误,界面程序授权失败!
            m_pPromptDlg->setContentStr(str);
            m_pPromptDlg->exec();

            //iniSetting.setValue("HMIDecrypt/ifdecrypt",0);

            return;
        }
    }
}

//超级用户退出程序
void MainWidgetFunction::slotExitApp()
{
    //是否退出程序

    m_pPromptDlg->initDialog(PromptDialog::BTN_OK_CANCEL);
    m_pPromptDlg->setTitleStr(tr("Prompt"));//提示

    QString str;
    str = tr("Whether to exit the program?");//是否退出程序？
    m_pPromptDlg->setContentStr(str);
    if(m_pPromptDlg->exec() == 1)
    {
        QApplication* app;
        app->exit(0);
    }
}

//超级用户版本恢复
void MainWidgetFunction::slotVerRecovery()
{
    //是否版本恢复

    m_pPromptDlg->initDialog(PromptDialog::BTN_OK_CANCEL);
    m_pPromptDlg->setTitleStr(tr("Prompt"));//提示

    QString str;
    str = tr("Is the version restored?");//是否版本恢复？
    m_pPromptDlg->setContentStr(str);
    if(m_pPromptDlg->exec() == 1)
    {
    }
}

//超级用户修改一级密码
void MainWidgetFunction::slotChangePassword()
{
    m_pPromptDlg->initDialog(PromptDialog::BTN_CHANGE_PASSWORD);//修改一级密码界面
    m_pPromptDlg->setTitleStr(tr("Modify the first level password"));
    m_pPromptDlg->setContentChangePasswordShow();
    if(m_pPromptDlg->exec() == 1)//点击确认按钮,确认修改密码
    {
        /*点击确定，首先检查编辑框中是否为空，然后检查两次输入的密码是否一致，
         一致就将原密码和新密码*/
        QString n_pwd = m_pPromptDlg->getInputNewPassword();//新密码
        QString rn_pwd = m_pPromptDlg->getInputConfirmPassword();//确认新密码
        if(n_pwd != rn_pwd)
        {
            //新密码和确认密码不一致
            m_pPromptDlg->initDialog(PromptDialog::BTN_OK);
            m_pPromptDlg->setTitleStr(tr("Prompt"));
            QString str;
            str = tr("The two passwords are inconsistent!");//新密码和确认密码不一致!
            m_pPromptDlg->setContentStr(str);
            m_pPromptDlg->exec();
        }
        else
        {
            g_passwordOne = n_pwd;//新的密码变成一级密码
            m_pPromptDlg->initDialog(PromptDialog::BTN_OK);
            m_pPromptDlg->setTitleStr(tr("Prompt"));
            QString str;
            str = tr("Password reset complete!");//密码修改成功!
            m_pPromptDlg->setContentStr(str);
            m_pPromptDlg->exec();
            g_pSettings->writeToIniFile("HMI/passwordOne",g_passwordOne);
        }
    }
}

//删除执行目录下的config.ini
void MainWidgetFunction::slotDeleteIni()
{
    m_pPromptDlg->initDialog(PromptDialog::BTN_OK_CANCEL);
    m_pPromptDlg->setTitleStr(tr("Prompt"));//提示

    QString str;
    str = tr("Do you delete the configuration file?");//是否删除配置文件？
    m_pPromptDlg->setContentStr(str);
    if(m_pPromptDlg->exec() == 1)
    {
        QDir apppath(qApp->applicationDirPath());

        //配置文件路径
        QString configfile;
        configfile = apppath.path() + apppath.separator() + "config.ini";
        QFile::remove(configfile);

        QString HMIConfigfile;
        HMIConfigfile = apppath.path() + apppath.separator() + "HMIConfig.ini";
        QFile::remove(HMIConfigfile);

        m_pPromptDlg->initDialog(PromptDialog::BTN_OK_CANCEL);
        m_pPromptDlg->setTitleStr(tr("Prompt"));

        QString str;
        str = tr("The settings take effect after restarting the interface!");//重启界面后设置生效!
        m_pPromptDlg->setContentStr(str);
        if(m_pPromptDlg->exec() == 1)
        {

#ifdef Q_OS_WIN
            qApp->exit();
#endif

#ifdef Q_OS_LINUX
            system("reboot");
#endif
        }
    }
}

//导入csv文件
void MainWidgetFunction::slotImportCSV()
{
    QString usbPath = detectUsb();
    if(usbPath.length() <= 0)
    {
        //优盘不存在
        m_pPromptDlg->initDialog(PromptDialog::BTN_OK);
        m_pPromptDlg->setTitleStr(tr("Prompt"));

        QString str;
        str = tr("USB flash drive is not detected!");//未检测到优盘！
        m_pPromptDlg->setContentStr(str);
        m_pPromptDlg->exec();
        return;
    }

    QString sPath = usbPath + CSV_PROGRESS;
    QDir apppath(qApp->applicationDirPath());
    QString tPath= apppath.absolutePath() + apppath.separator() + CSV_PROGRESS;
    QFile::remove(tPath);
    QFile::copy(sPath,tPath);

#ifdef Q_OS_LINUX
    system("sync");
#endif

    //成功导入csv文件！
    m_pPromptDlg->initDialog(PromptDialog::BTN_OK);
    m_pPromptDlg->setTitleStr(tr("Prompt"));

    QString str;
    str = tr("Import csv file successful!");//成功导入csv文件！
    m_pPromptDlg->setContentStr(str);
    m_pPromptDlg->exec();
}
//删除csv文件
void MainWidgetFunction::slotDeleteCSV()
{
    m_pPromptDlg->initDialog(PromptDialog::BTN_OK_CANCEL);
    m_pPromptDlg->setTitleStr(tr("Prompt"));//提示

    QString str;
    str = tr("Do you delete the csv file?");//是否删除csv文件？
    m_pPromptDlg->setContentStr(str);
    if(m_pPromptDlg->exec() == 1)
    {
        QDir apppath(qApp->applicationDirPath());

        //配置文件路径
        QString csvfile;
        csvfile = apppath.path() + apppath.separator() + CSV_PROGRESS;
        QFile::remove(csvfile);

#ifdef Q_OS_LINUX
        system("sync");
#endif
    }
}

//重置csv文件
void MainWidgetFunction::slotResetCSV()
{
    m_csvFileStrList.clear();

    QDir apppath(qApp->applicationDirPath());
    QString path = apppath.path() + apppath.separator() + CSV_PROGRESS;
    QFile file(path);
    if(!file.open(QIODevice::ReadOnly | QIODevice::Text))
    {
        qDebug() << "Open file failed!";
        return;
    }

    QTextStream out(&file);
    out.setCodec("GB2312");      //支持读取中文信息

    //遍历行
    for(int i = 0; !out.atEnd(); i++)
    {
        QString strLine = out.readLine();
        if(strLine.size() <= 0)
        {
            continue;
        }

        QStringList strlist = strLine.split(",", QString::SkipEmptyParts);    //根据","分隔开每行的列
        if(COLUMN_PRESSNUM < strlist.size())
        {
            if(i != 0)
            {
                strlist[COLUMN_PRESSNUM] = "0";
            }
            QString str;
            for(int m = 0; m < strlist.size(); m++)
            {
                str.append(strlist[m]);
                if(m != strlist.size() - 1)
                {
                    str.append(",");
                }
            }
            m_csvFileStrList.append(str);
        }
    }
    file.close();

    QTextCodec::setCodecForLocale(QTextCodec::codecForName("GBK"));

    QByteArray array;
    array.clear();
    for(int j = 0; j < m_csvFileStrList.size(); j++)
    {
        QString str = m_csvFileStrList[j];
        array.append(str.toLocal8Bit());
        if(j != m_csvFileStrList.size() - 1)
        {
            array.append('\n');
        }
    }

    QFile wfile(path);
    if (wfile.open(QIODevice::WriteOnly | QIODevice::Truncate | QIODevice::Text))
    {
        wfile.write(array);
#ifdef Q_OS_LINUX
        system("sync");
#endif
    }
    wfile.close();

    QTextCodec::setCodecForLocale(QTextCodec::codecForName("UTF-8"));

    QString iniPath = apppath.path() + apppath.separator() + "config.ini";
    QSettings setting(iniPath, QSettings::IniFormat);
    setting.setValue("Progress/getScore",0);
    m_getScore = 0;

    //成功导入csv文件！
    m_pPromptDlg->initDialog(PromptDialog::BTN_OK);
    m_pPromptDlg->setTitleStr(tr("Prompt"));

    QString str;
    str = tr("Reset succeeded!");//重置成功！
    m_pPromptDlg->setContentStr(str);
    m_pPromptDlg->exec();
}

//界面调试模式，调试模式时不需要密码      -rq
void MainWidgetFunction::slotDebugMode()
{
    m_pPromptDlg->initDialog(PromptDialog::BTN_OK_CANCEL);
    m_pPromptDlg->setTitleStr(tr("Prompt"));//提示

    QString str;
    if (g_emDebugMode == nodebugMode)
    {
        str = tr("Whether to enter debug mode?");//是否进入调试模式？
    }
    else
    {
        str = tr("whether to exit debug mode?");//是否退出调试模式？
    }
    m_pPromptDlg->setContentStr(str);
    if(m_pPromptDlg->exec() == 1)
    {
        if (g_emDebugMode == nodebugMode)
        {
            g_emDebugMode = debugMode;
        }
        else     //退出了调试模式
        {
            g_emDebugMode = nodebugMode;//全局的
            m_pPromptDlg->initDialog(PromptDialog::BTN_OK);
            m_pPromptDlg->setTitleStr(tr("Prompt"));//提示
            QString str2;
            str2 = tr("Please log in to super user again!");//请重新登录超级用户！
            m_pPromptDlg->setContentStr(str2);
            if(m_pPromptDlg->exec() == 1)   //退出超级用户界面
            {
                emit  siCloseRootPara();//关闭超级用户参数界面
            }
        }
        g_pSettings->writeToIniFile("HMI/debugMode",g_emDebugMode);//写入配置文件
        emit siDebugState();//主界面接收信号，调试模式时，界面不需要密码，界面标题变红
    }
}

//超级用户花样总清
void MainWidgetFunction::slotPatternClear()
{
    //是否花样总清
    m_pPromptDlg->initDialog(PromptDialog::BTN_OK_CANCEL);
    m_pPromptDlg->setTitleStr(tr("Prompt"));//提示
    QString str;
    str = tr("Is the pattern clear?");//是否花样总清？
    m_pPromptDlg->setContentStr(str);

    if(m_pPromptDlg->exec() == 1)
    {  //删除文件
        QDir apppath(qApp->applicationDirPath());
        QString targetDir = apppath.absolutePath() + apppath.separator();
        QString tPath = targetDir + PATTERNPATH;
        deleteDir(tPath);
    }
}

void MainWidgetFunction:: deleteDir(QString tPath)
{
    QDir dir(tPath);//项目中所保存的路径
    dir.setFilter(QDir::AllEntries | QDir::NoDotAndDotDot);//设置过滤
    QFileInfoList fileList = dir.entryInfoList();// 获取所有的文件信息
    foreach (QFileInfo file,fileList)//遍历文件信息
    {
        if (file.isFile()) //是文件，删除，文件夹也要删除
        {
            file.dir().remove(file.fileName());
        }
        else //递归删除
        {
            deleteDir(file.absoluteFilePath());
        }
    }
    dir.rmpath(dir.absolutePath());
    //检测是否删除
    QDir dir1(tPath);
    dir1.setFilter(QDir::AllEntries | QDir::NoDotAndDotDot);//设置过滤
    QFileInfoList fileList_1 = dir1.entryInfoList();//获取所有的文件信息
    if(fileList_1.size() == 0)
    {
        m_pPromptDlg->initDialog(PromptDialog::BTN_OK);
        m_pPromptDlg->setTitleStr(tr("Prompt"));
        m_pPromptDlg->setContentStr(tr("Delete complete!"));//删除完成!
        m_pPromptDlg->exec();
        emit siClearPattern();//清空当前选择的花样
        return;
    }
    else
    {
        deleteDir(tPath);
        //        m_pPromptDlg->initDialog(PromptDialog::BTN_OK);
        //        m_pPromptDlg->setTitleStr(tr("Prompt"));
        //        m_pPromptDlg->setContentStr(tr("Not cleaned up!"));//未清理完成!
        //        m_pPromptDlg->exec();
        //        return;
    }
}

void MainWidgetFunction::funSimulatedSewing()
{
    if(g_pMachine == NULL)
    {
        return;
    }
    m_pPromptDlg->initDialog(PromptDialog::BTN_OK_CANCEL);
    m_pPromptDlg->setTitleStr(tr("Simulated working"));//模拟工作
    QString str = tr("Whether to switch working status");//是否切换工作状态
    m_pPromptDlg->setContentStr(str);

   u32 workStatus = g_pMachine->getMcStatus().workStatus;

   if ((workStatus & WORK_STA_SIMULATE) == WORK_STA_SIMULATE) //模拟工作
   {
       if(m_pPromptDlg->exec() == 1)
       {
           g_pMachine->setNormalWork();
       }
   }
   else
   {
       if(m_pPromptDlg->exec() == 1)
       {
           g_pMachine->setSimulateWork();
       }
   }
}

void MainWidgetFunction::manualThreadCutting()
{
    m_pPromptDlg->initDialog(PromptDialog::BTN_OK_CANCEL);
    m_pPromptDlg->setTitleStr(tr("Manual thread cutting"));//手动剪线

    QString str;
    str = tr("The machine is about to move, please pay attention to safety!");//机器即将运动，请注意安全！
    m_pPromptDlg->setContentStr(str);

    if(m_pPromptDlg->exec() == 1)
    {
        if(g_pMachine != NULL)
        {
            g_pMachine->cutThreadByhand();
        }
    }
}

void MainWidgetFunction::makeup(int mode)
{
    m_pPromptDlg->initDialog(PromptDialog::BTN_OK_CANCEL);
    m_pPromptDlg->setTitleStr(tr("makeup sewing"));//补缝

    QString str;
    str = tr("The machine is about to move, please pay attention to safety!");//机器即将运动，请注意安全！
    m_pPromptDlg->setContentStr(str);

    if(m_pPromptDlg->exec() == 1)
    {
        if(g_pMachine != NULL)
        {
            g_pMachine->makeup(mode);
        }
    }
}

void MainWidgetFunction::headLiftUpDown()
{
    PromptDialog  promptDialog;
    promptDialog.initDialog(PromptDialog::BTN_OK_CANCEL);
    promptDialog.setTitleStr(tr("Head lifting and lowering"));//机头升降

    QString str;
    str = tr("The machine is about to move, please pay attention to safety!");//机器即将运动，请注意安全！
    promptDialog.setContentStr(str);

    if(promptDialog.exec() == 1)
    {
        if(g_pMachine != NULL)
        {
            //粗线布线机
            if(g_emMacType ==  MACHINE_THICK_WIRING)
            {
                g_pMachine->ThicklineSewHeadLiftUpDown();
            }
            else
            {
                g_pMachine->sewHeadLiftUpDown();
            }
        }
    }
}

void MainWidgetFunction::headLifting()
{
    PromptDialog  promptDialog;
    promptDialog.initDialog(PromptDialog::BTN_OK_CANCEL);
    promptDialog.setTitleStr(tr("Head lifting"));//机头上升

    QString str;
    str = tr("The machine is about to move, please pay attention to safety!");//机器即将运动，请注意安全！
    promptDialog.setContentStr(str);

    if(promptDialog.exec() == 1)
    {
        if(g_pMachine != NULL)
        {
            g_pMachine->sewHeadLiftUp();
        }
    }
}

void MainWidgetFunction::funSetAnchorPoint(QString filePath,int x,int y,int showFlag, bool allToReset, bool isSendPatternHead)
{
    if(filePath.length() <= 0)
    {
        return;
    }

    m_pPromptDlg->initDialog(PromptDialog::BTN_OK_CANCEL);
    m_pPromptDlg->setTitleStr(tr("Set anchor point"));//定定位点
    QString str = tr("Whether to set the current point as the start point?");//是否将当前点设置为定位点?
    m_pPromptDlg->setContentStr(str);

    int setFlag = 1;
    if(showFlag == 1)
    {
        setFlag = m_pPromptDlg->exec();
    }

    if(setFlag == 1)
    {
        if(g_pCurEmbData != NULL)
        {
            g_pCurEmbData->setAnchorPosition(x,y);//将主控当前机头存在ds16头文件里
            //改变中间数据（ds16）的头文件
        }
        if(isSendPatternHead)
            sendPatternHead(filePath);//发送花样ds16头文件

        //每次点击选择花样的时候才会生成ds16数据，其他时候就是给下位机发头文件
        //dsr,dst整个文件->中间数据->ds16
        writePonitToFile(filePath,x,y,1);  //将新的起始点，机头，写回到（dst，dsr）源文件中

        //流程复位
        if(allToReset)
            g_pMachine->allToReset();

        slotCalMachineProgress(CSV_00_CODE_2);
    }
}

//平板切割机（定定位点）
void MainWidgetFunction::funSetAnchorPointForFlat(QString filePath,int x, int y,s16 showFlag,s16 saveFlag)
{
    if(showFlag == 1)
    {
        m_pPromptDlg->initDialog(PromptDialog::BTN_OK_CANCEL);
        m_pPromptDlg->setTitleStr(tr("Set anchor point"));//定定位点
        QString str = tr("Whether to set the current point as the anchor point?");//是否将当前点设置为定位点?
        m_pPromptDlg->setContentStr(str);
        if(m_pPromptDlg->exec() != 1)
            return;
    }

    if(saveFlag != 0)
    {
        //写入配置文件
        g_pSettings->writeToIniFile("FlatPanel/AnchorPointX", x);
        g_pSettings->writeToIniFile("FlatPanel/AnchorPointY", y);
    }

    if(g_pCurEmbData != NULL && filePath.length() > 0)
    {
        if(g_emMacType == MACHINE_DRAWING)
        {
            g_pCurEmbData->setAnchorPosition(x,y);//设置定位点
            //根据定位点计算起始点
            //int maxX = g_pCurEmbData->getMaxX();
            int minX = g_pCurEmbData->getMinX();
            int begX = g_pCurEmbData->getBeginX();
            int cx = x - (minX - begX);
            //int maxY = g_pCurEmbData->getMaxY();
            int minY = g_pCurEmbData->getMinY();
            int begY = g_pCurEmbData->getBeginY();
            int cy = y - (minY - begY);
            g_pCurEmbData->setStartPosition(cx,cy);//设置起始点
            sendPatternHead(filePath);//发送花样ds16头文件
        }
        else if(g_emMacType == MACHINE_FLATCUTTINGMAC)  //平板切割机
        {
            g_pCurEmbData->setAnchorPosition(x,y);//设置定位点
            g_pCurEmbData->setStartPosition(x,y);//设置起始点
            sendPatternHead(filePath);//发送花样ds16头文件
        }
        else
        {
            g_pCurEmbData->setAnchorPosition(x,y);//设置定位点
            g_pSettings->writeToIniFile("FlatPanel/AnchorPointX",x);
            g_pSettings->writeToIniFile("FlatPanel/AnchorPointY",y);
            //根据定位点计算起始点

            int maxX = g_pCurEmbData->getMaxX();
            //int minX = g_pCurEmbData->getMinX();
            int begX = g_pCurEmbData->getBeginX();
            //起始点坐标 = dsr头文件定位点+dsr头文件起始点+第一针坐标
            int cx = x - (maxX - begX);//第一针坐标
            int maxY = g_pCurEmbData->getMaxY();
            //int minY = g_pCurEmbData->getMinY();
            int begY = g_pCurEmbData->getBeginY();
            int cy = y - (maxY - begY);


            g_pCurEmbData->setStartPosition(cx,cy);//设置起始点
            sendPatternHead(filePath);//发送花样ds16头文件
        }
    }
}

void MainWidgetFunction::funBackAnchorPoint()
{
    m_pPromptDlg->initDialog(PromptDialog::BTN_OK_CANCEL);
    m_pPromptDlg->setTitleStr(tr("Back anchor point"));//回定位点
    QString str;
    str = tr("The machine is about to move, please pay attention to safety!");//机器即将运动，请注意安全！
    m_pPromptDlg->setContentStr(str);

    if(m_pPromptDlg->exec() == 1)
    {
        if(g_pMachine != NULL)
        {
            g_pMachine->gotoAnchor();
            slotCalMachineProgress(CSV_00_CODE_3);
        }
    }
}

void MainWidgetFunction::funBackShuttlePos()
{
    m_pPromptDlg->initDialog(PromptDialog::BTN_OK_CANCEL);
    m_pPromptDlg->setTitleStr(tr("Back shuttle pos"));//回换梭位

    QString str;
    str = tr("The machine is about to move, please pay attention to safety!");//机器即将运动，请注意安全！
    m_pPromptDlg->setContentStr(str);

    if(m_pPromptDlg->exec() == 1)
    {
        if(g_pMachine != NULL)
        {
            g_pMachine->gotoShuttlePos();
        }
    }
}

void MainWidgetFunction::funNeedleShuttleReset()
{
    m_pPromptDlg->initDialog(PromptDialog::BTN_OK_CANCEL);
    m_pPromptDlg->setTitleStr(tr("Needle shuttle adjust"));//针梭校对

    QString str;
    str = tr("The machine is about to move, please pay attention to safety!");//机器即将运动，请注意安全！
    m_pPromptDlg->setContentStr(str);

    if(m_pPromptDlg->exec() == 1)
    {
        if(g_pMachine != NULL)
        {
            g_pMachine->msAdjust(0);
        }
    }
}

void MainWidgetFunction::funKnifeCollect()
{
    if(promptBox(tr("Knife pressure collection")) != 1)//刀压采集
        return;
    if(g_pMachine != NULL)
    {
        g_pMachine->manualAction(KNIFE_COLLECT);
    }
}

void MainWidgetFunction::funKnifeTest()
{
    m_pPromptDlg->initDialog(PromptDialog::BTN_KNIFE_PRESSURE);
    m_pPromptDlg->setTitleStr(tr("Knife pressure test"));//刀压测试
    m_pPromptDlg->exec();
}

void MainWidgetFunction::funFanArea()
{
    m_pPromptDlg->initDialog(PromptDialog::BTN_FAN_AREA);
    m_pPromptDlg->setTitleStr(tr("Fan area"));//风机区域
    m_pPromptDlg->exec();
}

void MainWidgetFunction::funSpdSelect()
{
    m_pPromptDlg->initDialog(PromptDialog::BTN_SPD_SELECT);
    m_pPromptDlg->setTitleStr(tr("Speed Select"));//速度选择
    m_pPromptDlg->exec();
}

void MainWidgetFunction::funSetKnifeTestPos()
{
    if(promptBox(tr("Set the position for tool pressure detection")) != 1)//设置刀压检测位置
        return;
    if(g_pMachine != NULL)
    {
        g_pMachine->manualAction(SET_KNIFETEST_POS);
    }
}

void MainWidgetFunction::funSetKnifeRotPos()
{
    if(promptBox(tr("Set passive knife rotation position")) != 1)//设置被动刀旋转位置
        return;
    if(g_pMachine != NULL)
    {
        g_pMachine->manualAction(SET_KNIFEROT_POS);
    }
}

void MainWidgetFunction::funRotPassiveKnife()
{
    if(promptBox(tr("Rotating passive knife")) != 1)//旋转被动刀
        return;

    if(g_pMachine != NULL)
    {
        g_pMachine->manualAction(PASSIVE_KNIFE_ROT);
    }
}

void MainWidgetFunction::funRotPassiveKnife1()
{
     if(promptBox(tr("Rotating passive knife 1")) != 1)//旋转被动刀1
         return;

     if(g_pMachine != NULL)
     {
         g_pMachine->manualAction(U1_PASSIVE_KNIFE_ROT);
     }
}

void MainWidgetFunction::funRotPassiveKnife2()
{
    if(promptBox(tr("Rotating passive knife 2")) != 1)//旋转被动刀2
        return;

    if(g_pMachine != NULL)
    {
        g_pMachine->manualAction(U2_PASSIVE_KNIFE_ROT);
    }
}

void MainWidgetFunction::funCrossCut()
{
    if(promptBox(tr("Cross cutting")) != 1)//横切
        return;

    if(g_pMachine != NULL)
    {
        g_pMachine->manualAction(CROSS_CUT);
    }
}

void MainWidgetFunction::funThickWiringmac(int funEnum)
{
    QString str;
    int funType = -1;

    switch (funEnum) {
    case FUN_MS_TO_ANGLE:
        str = tr("Spindle to specified angle");//主轴去指定角度
        funType = MS_TO_ANGLE;
        break;
    case FUN_WIRE_MS_RUN:
        str = tr("Spindle grinding machine");//主轴研车
        funType = WIRE_MS_RUN;
        break;
    case FUN_ROT_TO_ANGLE:
        str = tr("Rotate the motor to the specified angle");//旋转电机去指定角度
        funType = ROT_TO_ANGLE;
        break;
    case FUN_AUTO_PULL:
        str = tr("Automatic material pulling");//自动拉料
        funType = AUTO_PULL;
        break;
    case FUN_CUT_UD:
        str = tr("Cut the bottom surface line");//剪底面线
        funType = CUT_UD;
        break;
    case FUN_CUT_WIRE:
        str = tr("Cutting resistance wire");//剪电阻丝
        funType = CUT_WIRE;
        break;
    case FUN_GOTO_PULLPOS:
        str = tr("Starting point of pull back material");//回拉料起始点
        funType = GOTO_PULLPOS;
        break;
    case FUN_JAW_WORK:
        str = tr("Working status of fabric clamping");//夹布工作状态
        funType = JAW_WORK;
        break;
    case FUN_JAW_FEED:
        str = tr("Cloth loading status");//夹布上料状态
        funType = JAW_FEED;
        break;
    case FUN_ZIGZAG_POS1:
        str = tr("To swing position 1");//去摆动位1
        funType = ZIGZAG_POS1;
        break;
    case FUN_ZIGZAG_POS2:
        str = tr("Go to swing position 2");//去摆动位2
        funType = ZIGZAG_POS2;
        break;
    case FUN_YPB_MOVE:
        str = tr("Manual material pulling");//手动拉料
        funType = YPB_MOVE;
        break;
    case FUN_AUTO_CHANGE_ONE_SHUT:
        str = tr("Automatically switch to another shuttle");//自动换一个梭
        funType = AUTO_CHANGE_ONE_SHUT;
        break;
    case FUN_INSTALL_FIRST_BOBBIN:
        str = tr("Install the first shuttle shell");//安装第一个梭壳
        funType = INSTALL_FIRST_BOBBIN;
        break;
    case FUN_SHUT_FROM_PLATE_TO_HEAD:
        str = tr("Take the rotary shuttle from the machine head to the shuttle disc");//将旋梭从机头拿到梭盘
        funType = SHUT_FROM_PLATE_TO_HEAD;
        break;
    case FUN_SHUT_FROM_HEAD_TO_PLATE:
        str = tr("Take the rotary shuttle from the machine head to the shuttle disc");//将旋梭从机头拿到梭盘
        funType = SHUT_FROM_HEAD_TO_PLATE;
        break;
    case FUN_SHUT_INTO_TAKE_PLATE:
        str = tr("Entering the state of replacing the shuttle disk");//进入更换梭盘状态
        funType = SHUT_INTO_TAKE_PLATE ;
        break;
    case FUN_SHUT_INTO_INDX_STA:
        str = tr("Entering sewing mode");//进入缝纫状态
        funType = SHUT_INTO_INDX_STA;
        break;
    case FUN_SHUT_FEED_STATE:
        str = tr("Entering feed mode");//进入送料状态
        funType = SHUT_FEED_STATE;
        break;
    case FUN_SHUT_BACK_STATE:
        str = tr("Entering take back mode");//进入收料状态
        funType = SHUT_BACK_STATE;
        break;
    default:
        break;
    }

    if(promptBox(str) != 1)//设置被动刀旋转位置
        return;
    if((g_pMachine != NULL) && (funType != -1))
    {
        g_pMachine->manualAction(funType);
    }
}

/**
 * @brief 机器运动提示框
 * @param title
 * @return
 */
int MainWidgetFunction::promptBox(QString title)
{
    m_pPromptDlg->initDialog(PromptDialog::BTN_OK_CANCEL);
    m_pPromptDlg->setTitleStr(title);
    QString str;
    str = tr("The machine is about to move, please pay attention to safety!");//机器即将运动，请注意安全！
    m_pPromptDlg->setContentStr(str);

    return m_pPromptDlg->exec();
}

//win下关机按钮
void MainWidgetFunction::funShutDown()
{
    //是否关闭计算机
    m_pPromptDlg->initDialog(PromptDialog::BTN_OK_CANCEL);
    m_pPromptDlg->setTitleStr(tr("Prompt"));//提示

    QString str;
    str = tr("Whether to shut down the computer?");//是否关闭计算机？
    m_pPromptDlg->setContentStr(str);
    if(m_pPromptDlg->exec() == 1)
    {
        system("shutdown -s -t 00");//电脑关机
    }
}

//自动换一个梭
void MainWidgetFunction::funChangeOneShuttle()
{
    m_pPromptDlg->initDialog(PromptDialog::BTN_OK_CANCEL);
    m_pPromptDlg->setTitleStr(tr("Prompt"));//提示
    QString str;
    str = tr("Whether to set to change a shuttle automatically?");//是否设置自动换一个梭？
    m_pPromptDlg->setContentStr(str);
    if(m_pPromptDlg->exec() == 1)
    {
        if(g_pMachine != NULL)
        {
            g_pMachine->changeOneShuttle();
        }
    }
}

// 安装第一个梭壳
void MainWidgetFunction::InstallTheFirstShuttleShell()
{
    m_pPromptDlg->initDialog(PromptDialog::BTN_OK_CANCEL);
    m_pPromptDlg->setTitleStr(tr("Prompt"));//提示
    QString str;
    str = tr("Whether to set to the first shuttle shell installed?");//是否安装第一个梭壳？
    m_pPromptDlg->setContentStr(str);
    if(m_pPromptDlg->exec() == 1)
    {
        if(g_pMachine != NULL)
        {
            g_pMachine->installShuttle();
        }
    }
}

// 将旋梭从梭盘拿到机头
void MainWidgetFunction::ShuttleFromTrayToHead()
{
    m_pPromptDlg->initDialog(PromptDialog::BTN_OK_CANCEL);
    m_pPromptDlg->setTitleStr(tr("Prompt"));//提示
    QString str;
    str = tr("Whether to take the rotary shuttle from the shuttle tray to the machine head?");//是否将旋梭从梭盘拿到机头？
    m_pPromptDlg->setContentStr(str);
    if(m_pPromptDlg->exec() == 1)
    {
        if(g_pMachine != NULL)
        {
            g_pMachine->shuttleToHead();
        }
    }
}

// 将旋梭从机头拿到梭盘
void MainWidgetFunction::ShuttleFromHeadToTray()
{
    m_pPromptDlg->initDialog(PromptDialog::BTN_OK_CANCEL);
    m_pPromptDlg->setTitleStr(tr("Prompt"));//提示
    QString str;
    str = tr("Whether to take the rotary shuttle from the machine head to the shuttle tray?");//是否将旋梭从机头拿到梭盘？
    m_pPromptDlg->setContentStr(str);
    if(m_pPromptDlg->exec() == 1)
    {
        if(g_pMachine != NULL)
        {
            g_pMachine->headToShuttle();
        }
    }
}


// 改变弹窗位置
void MainWidgetFunction::moveDlgPos(void)
{
    m_pPromptDlg->move((GLB_SCR_WIGHT*getFactoryX()-m_pPromptDlg->width())/2+g_mainWidgetPos.x(),(GLB_SCR_HEIGHT*getFactoryY()-m_pPromptDlg->height())/2+g_mainWidgetPos.y());
    m_pSystemManageDlg->move(g_mainWidgetPos.x(),g_mainWidgetPos.y());
    m_pDebugInfoDlg->move(101*getFactoryX()+g_mainWidgetPos.x(),36*getFactoryX()+g_mainWidgetPos.y());
}

void MainWidgetFunction::funAllMtZero()
{
    m_pPromptDlg->initDialog(PromptDialog::BTN_OK_CANCEL);
    m_pPromptDlg->setTitleStr(tr("AllSpindleZeroPositions"));//所有主轴零位
    QString str = tr("The machine is about to move, please pay attention to safety!");//机器即将运动，请注意安全！
    m_pPromptDlg->setContentStr(str);
    if((m_pPromptDlg->exec() == 1) && (g_pMachine != NULL))
    {
//        if(g_emMacType == MACHINE_MULTINEEDLEROTARY)
//        {

//        }else
        {
            g_pMachine->motoToZero(MT_ALLZ);
        }
    }
}

//启动工作
void MainWidgetFunction::funStartWork()
{
    m_pPromptDlg->initDialog(PromptDialog::BTN_OK_CANCEL);
    m_pPromptDlg->setTitleStr(tr("Start work"));//启动工作
    QString str = tr("The machine is about to move, please pay attention to safety!");//机器即将运动，请注意安全！
    m_pPromptDlg->setContentStr(str);
    if((m_pPromptDlg->exec() == 1) && (g_pMachine != NULL))
    {
        g_pMachine->startWork();
    }
}

//梭加油
void MainWidgetFunction::funShuttleRef()
{    
    if((g_pMachine != NULL))
    {
        if(m_SopenFlag!=0)
        {
            g_pMachine->outputCtrl(0x0099, UP_OPEN_ON, 0);
            m_SopenFlag = 0;
        }
        else
        {
            g_pMachine->outputCtrl(0x0099, DOWN_CLOSE_OFF, 0);
            m_SopenFlag = 1;
        }
    }
}

//针加油
void MainWidgetFunction::funNeedleRef()
{
    if((g_pMachine != NULL))
    {
        if(m_NopenFlag!=0)
        {
            g_pMachine->outputCtrl(0x0098, UP_OPEN_ON, 0);
            m_NopenFlag = 0;
        }
        else
        {
            g_pMachine->outputCtrl(0x0098, DOWN_CLOSE_OFF, 0);
            m_NopenFlag = 1;
        }
    }
}

void MainWidgetFunction::funAllMtG()
{
    m_pPromptDlg->initDialog(PromptDialog::BTN_OK_CANCEL);
    m_pPromptDlg->setTitleStr(tr("AllSpindleHookLines"));//所有主轴勾线
    QString str = tr("The machine is about to move, please pay attention to safety!");//机器即将运动，请注意安全！
    m_pPromptDlg->setContentStr(str);
    if((m_pPromptDlg->exec() == 1) && (g_pMachine != NULL))
    {
        g_pMachine->motoToZero(MT_ALLG);
    }
}

void MainWidgetFunction::funAllMtM()
{
    m_pPromptDlg->initDialog(PromptDialog::BTN_OK_CANCEL);
    m_pPromptDlg->setTitleStr(tr("AllSpindleJogs"));//所有主轴点动
    QString str = tr("The machine is about to move, please pay attention to safety!");//机器即将运动，请注意安全！
    m_pPromptDlg->setContentStr(str);
    if((m_pPromptDlg->exec() == 1) && (g_pMachine != NULL))
    {
        g_pMachine->motoToZero(MT_ALLM);
    }
}
// 针梭校对
void MainWidgetFunction::funMainshaftAdjust()
{
    m_pPromptDlg->initDialog(PromptDialog::BTN_OK_CANCEL);
    m_pPromptDlg->setTitleStr(tr("NeedleShuttleProofreading"));    // 针梭校对
    QString str = tr("The machine is about to move, please pay attention to safety!");//机器即将运动，请注意安全！
    m_pPromptDlg->setContentStr(str);
    if((m_pPromptDlg->exec() == 1) && (g_pMachine != NULL))
    {
        g_pMachine->motoToZero(MAINSHAFT_ADJUST);
    }
}

void MainWidgetFunction::funAllMainShaftRun()
{
    if(g_emMacType == MACHINE_THICK_WIRING)
    {
        m_pPromptDlg->initDialog(PromptDialog::BTN_SPINDLE_GRANDE);
        m_pPromptDlg->setTitleStr(tr("AllMainShaftRun"));//所有主轴研车
        m_pPromptDlg->exec();
    }
    else
    {
        m_pPromptDlg->initDialog(PromptDialog::BTN_OK_CANCEL);
        m_pPromptDlg->setTitleStr(tr("AllMainShaftRun"));    // 所有主轴研车
        QString str = tr("The machine is about to move, please pay attention to safety!");//机器即将运动，请注意安全！
        m_pPromptDlg->setContentStr(str);
        if((m_pPromptDlg->exec() == 1) && (g_pMachine != NULL))
        {
            g_pMachine->manualAction(ALL_MS_RUN);
        }
    }

}
// 粗线布线机针梭校对
void MainWidgetFunction::ThicklinefunMainshaftAdjust()
{
    m_pPromptDlg->initDialog(PromptDialog::BTN_OK_CANCEL);
    m_pPromptDlg->setTitleStr(tr("NeedleShuttleProofreading"));    // 针梭校对
    QString str = tr("The machine is about to move, please pay attention to safety!");//机器即将运动，请注意安全！
    m_pPromptDlg->setContentStr(str);
    if((m_pPromptDlg->exec() == 1) && (g_pMachine != NULL))
    {
        g_pMachine->manualAction(MAINSHAFT_ADJUST);
    }
}
//自动拉料
void MainWidgetFunction::AutomaticMaterialPull()
{
    m_pPromptDlg->initDialog(PromptDialog::BTN_AUTOMATIC_PULLMA);
    m_pPromptDlg->setTitleStr(tr("Automatic material pulling"));//自动拉料
    m_pPromptDlg->exec();

//    m_pPromptDlg->initDialog(PromptDialog::BTN_OK_CANCEL);
//    m_pPromptDlg->setTitleStr(tr("Automatic material pulling"));    // 自动拉料
//    QString str = tr("The machine is about to move, please pay attention to safety!");//机器即将运动，请注意安全！
//    m_pPromptDlg->setContentStr(str);
//    if((m_pPromptDlg->exec() == 1) && (g_pMachine != NULL))
//    {
//        g_pMachine->manualAction(AUTO_PULL);
//    }
}
//剪底面线
void MainWidgetFunction::CutBottomLine()
{
    m_pPromptDlg->initDialog(PromptDialog::BTN_OK_CANCEL);
    m_pPromptDlg->setTitleStr(tr("Cut the bottom surface line"));    // 剪底面线
    QString str = tr("The machine is about to move, please pay attention to safety!");//机器即将运动，请注意安全！
    m_pPromptDlg->setContentStr(str);
    if((m_pPromptDlg->exec() == 1) && (g_pMachine != NULL))
    {
        g_pMachine->manualAction(CUT_UD);
    }
}
//剪电阻丝
void MainWidgetFunction::CutResistanceWire()
{
    m_pPromptDlg->initDialog(PromptDialog::BTN_OK_CANCEL);
    m_pPromptDlg->setTitleStr(tr("Cutting resistance wire"));    // 剪电阻丝
    QString str = tr("The machine is about to move, please pay attention to safety!");//机器即将运动，请注意安全！
    m_pPromptDlg->setContentStr(str);
    if((m_pPromptDlg->exec() == 1) && (g_pMachine != NULL))
    {
        g_pMachine->manualAction(CUT_WIRE);
    }
}
//回拉料起始点
void MainWidgetFunction::StartPointOfBackMaterial()
{
    m_pPromptDlg->initDialog(PromptDialog::BTN_OK_CANCEL);
    m_pPromptDlg->setTitleStr(tr("Starting point of pull back material"));    // 回拉料起始点
    QString str = tr("The machine is about to move, please pay attention to safety!");//机器即将运动，请注意安全！
    m_pPromptDlg->setContentStr(str);
    if((m_pPromptDlg->exec() == 1) && (g_pMachine != NULL))
    {
        g_pMachine->manualAction(GOTO_PULLPOS);
    }
}
// 夹布工作状态
void MainWidgetFunction::WorkStatusOfClamp()
{
    m_pPromptDlg->initDialog(PromptDialog::BTN_OK_CANCEL);
    m_pPromptDlg->setTitleStr(tr("Working status of fabric clamping"));    // 夹布工作状态
    QString str = tr("The machine is about to move, please pay attention to safety!");//机器即将运动，请注意安全！
    m_pPromptDlg->setContentStr(str);
    if((m_pPromptDlg->exec() == 1) && (g_pMachine != NULL))
    {
        g_pMachine->manualAction(JAW_WORK);
    }
}
// 夹布上料状态
void MainWidgetFunction::ClothStatus()
{
    m_pPromptDlg->initDialog(PromptDialog::BTN_OK_CANCEL);
    m_pPromptDlg->setTitleStr(tr("Cloth loading status"));    // 夹布上料状态
    QString str = tr("The machine is about to move, please pay attention to safety!");//机器即将运动，请注意安全！
    m_pPromptDlg->setContentStr(str);
    if((m_pPromptDlg->exec() == 1) && (g_pMachine != NULL))
    {
        g_pMachine->manualAction(JAW_FEED);
    }
}
// 去摆动位1
void MainWidgetFunction::SwingPositionOne()
{
    m_pPromptDlg->initDialog(PromptDialog::BTN_OK_CANCEL);
    m_pPromptDlg->setTitleStr(tr("To swing position 1"));   // 去摆动位1
    QString str = tr("The machine is about to move, please pay attention to safety!");//机器即将运动，请注意安全！
    m_pPromptDlg->setContentStr(str);
    if((m_pPromptDlg->exec() == 1) && (g_pMachine != NULL))
    {
        g_pMachine->manualAction(ZIGZAG_POS1);
    }
}
// 去摆动位2
void MainWidgetFunction::SwingPositionTwo()
{
    m_pPromptDlg->initDialog(PromptDialog::BTN_OK_CANCEL);
    m_pPromptDlg->setTitleStr(tr("To swing position 2"));   // 去摆动位2
    QString str = tr("The machine is about to move, please pay attention to safety!");//机器即将运动，请注意安全！
    m_pPromptDlg->setContentStr(str);
    if((m_pPromptDlg->exec() == 1) && (g_pMachine != NULL))
    {
        g_pMachine->manualAction(ZIGZAG_POS2);
    }
}
// 手动拉料
void MainWidgetFunction::ManualMaterial()
{
    m_pPromptDlg->initDialog(PromptDialog::BTN_OK_CANCEL);
    m_pPromptDlg->setTitleStr(tr("Manual material pulling"));   // 手动拉料
    QString str = tr("The machine is about to move, please pay attention to safety!");//机器即将运动，请注意安全！
    m_pPromptDlg->setContentStr(str);
    if((m_pPromptDlg->exec() == 1) && (g_pMachine != NULL))
    {
        g_pMachine->manualAction(YPB_MOVE);
    }
}
// 进入更换梭盘状态
void MainWidgetFunction::ShuttleState()
{
    m_pPromptDlg->initDialog(PromptDialog::BTN_OK_CANCEL);
    m_pPromptDlg->setTitleStr(tr("Prompt"));//提示
    QString str;
    str = tr("Whether to entering the state of replacing the shuttle disk?");//是否进入更换梭盘状态？
    m_pPromptDlg->setContentStr(str);
    if(m_pPromptDlg->exec() == 1)
    {
        if(g_pMachine != NULL)
        {
            g_pMachine->manualAction(SHUT_INTO_TAKE_PLATE);
        }
    }
}
// 进入缝纫状态
void MainWidgetFunction::SewState()
{
    m_pPromptDlg->initDialog(PromptDialog::BTN_OK_CANCEL);
    m_pPromptDlg->setTitleStr(tr("Prompt"));//提示
    QString str;
    str = tr("Whether to entering the state of sewing mode?");//是否进入更换梭盘状态？
    m_pPromptDlg->setContentStr(str);
    if(m_pPromptDlg->exec() == 1)
    {
        if(g_pMachine != NULL)
        {
            g_pMachine->manualAction(SHUT_INTO_INDX_STA);
        }
    }
}

// 进入送料状态
void MainWidgetFunction::FeedState()
{
    m_pPromptDlg->initDialog(PromptDialog::BTN_OK_CANCEL);
    m_pPromptDlg->setTitleStr(tr("Prompt"));//提示
    QString str;
    str = tr("Whether to entering the state of feed mode?");//是否进入进入送料状态？
    m_pPromptDlg->setContentStr(str);
    if(m_pPromptDlg->exec() == 1)
    {
        if(g_pMachine != NULL)
        {
            g_pMachine->manualAction(SHUT_FEED_STATE);
        }
    }
}

// 进入收料状态
void MainWidgetFunction::BackState()
{
    m_pPromptDlg->initDialog(PromptDialog::BTN_OK_CANCEL);
    m_pPromptDlg->setTitleStr(tr("Prompt"));//提示
    QString str;
    str = tr("Whether to entering the state of back mode?");//是否进入收料状态？
    m_pPromptDlg->setContentStr(str);
    if(m_pPromptDlg->exec() == 1)
    {
        if(g_pMachine != NULL)
        {
            g_pMachine->manualAction(SHUT_BACK_STATE);
        }
    }
}

// 梭芯底线显示
//根据换梭芯提醒功能来决定具体使用哪个参数,如果选择1或3,按针数计数,当前梭芯底线剩余量就等于底线长度计数/换梭针数计数得到的百分比
//如果选择2按片数计数,当前梭芯底线剩余量就等于底线片数计数/换梭片数计数得到的百分比
//如果选择0不提醒,就按照1按针数计数处理

void MainWidgetFunction::ShuttleBottemLine()
{
    int funtion = g_pMachine->getWkPara().buf[70];     //换梭芯提醒功能, 0, 不启用该功能; 1, 按针度计数延迟提醒; 2, 按片数计数; 3, 按长度立刻提醒; 默认0

    int quantityNeedle = g_pMachine->getWkPara().buf[71]; //换梭针数计数

    int quantityPiece = g_pMachine->getWkPara().buf[72]; //换梭片数计数

    int bottomLength = m_mcStatus.btrdLength; // 底线长度计数
    int bottomPiece = m_mcStatus.btrdPics; // 底线片数计数

    int remainShuttle = m_mcStatus.motosPos4; //剩余梭芯数量

    int NowBottom = 0;   //梭芯底线剩余量


    //除数不能为零,如果其中有一个为零则返回
    if(quantityPiece == 0 || quantityNeedle == 0)
    {
        return ;
    }
    else
    {
        if(remainShuttle > 8 || remainShuttle < 0)
        {
            return ;
        }
        else
        {
            if(funtion ==  2)
            {
                NowBottom = (bottomPiece*100)/quantityPiece;
            }
            else
            {
                NowBottom = (bottomLength*100)/quantityNeedle;
            }
        }

    }

    m_shuttleDlg->showShuttlenumber(remainShuttle, NowBottom);

    if(m_shuttleDlg->exec() == 1)
    {
        if(g_pMachine != NULL)
        {

        }
    }
//    m_pPromptDlg->initDialog(PromptDialog::BTN_OK_CANCEL);
//    m_pPromptDlg->setTitleStr(tr("Prompt"));//提示
//    QString str;
//    str = tr("Whether to entering the state of back mode?");//是否进入收料状态？
//    m_pPromptDlg->setContentStr(str);
//    if(m_pPromptDlg->exec() == 1)
//    {
//        if(g_pMachine != NULL)
//        {
//            g_pMachine->manualAction(SHUT_BACK_STATE);
//        }
//    }
}
